Jul 16 2011

Moving methods from one class to another

Category: Pythontuxie @ 16:23

Not too often you need to move a method from one class to another, but sometimes you just do. You may be tempted to do something like this:

>>> class A(object):
... def b(self):
... print('b')
>>> A.b

>>> class B(object):
... pass
>>> B.b = A.b
>>> B.b

>>> b = B()
>>> b.b

>>> b.b()
Traceback (most recent call last):
File "", line 1, in
TypeError: unbound method b() must be called with A instance as first argument (got nothing instead)

But as noted, it doesn’t work. In python even functions are objects, and A.b is an instance of your method. What you need is the class itself, the “raw” function:

>>> B.b = A.b.__func__
>>> B.b

>>> b.b()


I disabled comments because I was sick of spam. If you want to comment on anything write me to alvaro@(this domain).