Reusing object methods?

Leif K-Brooks eurleif at ecritters.biz
Fri Apr 29 14:25:45 EDT 2005


Ivan Voras wrote:
> I want to 'reuse' the same method from class A in class B, and without 
> introducing a common ancestor for both of them - is this possible in an 
> elegant, straightforward way?

 >>> import new
 >>>
 >>> class A:
...     def foo(self):
...         print "Hello, %s!" % self.__class__.__name__
...
 >>> class B:
...     def __init__(self):
...         self.foo = new.instancemethod(A.foo.im_func, self, B)
...
 >>> A().foo()
Hello, A!
 >>> B().foo()
Hello, B!



More information about the Python-list mailing list