dynamic bases
Niels Diepeveen
niels at endea.demon.nl
Fri Jul 21 12:51:11 EDT 2000
Balazs Scheidler schreef:
> My other attempt was to use __getattr__ hooks to return attributes in a way
> that attributes of A are returned in case __dict__ of B doesn't contain a
> given name. Functions were bound to the instance of B, then the Python
> interpreter complained that self is not a subclass of B.
If you want to do it as cleanly as possible, you can use something like
this:
class DynaMethod:
def __init__(self, instance, function):
self.instance = instance
self.function = function
def __call__(self, *args, **kwargs):
apply(self.function, (self.instance,) + args, kwargs)
if __name__ == '__main__':
# test code
def method_a(self):
print 'Doing a now on object %s' % id(self)
def method_b(self, arg1):
print 'Doing b with argument %s' % repr(arg1)
class A:
def __init__(self):
self.method_a = DynaMethod(self, method_a)
self.method_b = DynaMethod(self, method_b)
a = A()
print 'Created instance %s' % id(a)
dir(a)
a.method_a()
a.method_b('test')
This does take some extra memory and time though. A more efficient, but
probably implementation-dependent way would be to use
new.instancemethod().
--
Niels Diepeveen
Endea automatisering
More information about the Python-list
mailing list