Adding method from one class to another class or to instance of another class

Terry Reedy tjreedy at
Fri Jul 24 21:17:15 CEST 2009

marekw2143 wrote:
> Hi,
> I have one class (A) that has defined method createVars. I would like
> to add that method to class B
> The code looks like this:
> class A(object):
>    def createVars(self):
>       self.v1 = 1
>       self.v2 = 3
>       pass
> class B(object):
>    pass
> I don't want to use inheritance (because class A has many methods
> defined that class B doesn't need).
> When I try the folloowing:
> B.createVars = C.createVars

  you meant A.createVars

> B().createVars()
> then the following error occurs:
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: unbound method createVars() must be called with A instance
> as first argument (got nothing instead)

In 3.1, your example works fine. The difference is that in 2.x, 
B.createVars is a method wrapperthat wraps the function, whereas in 3.1, 
it is the function itself. For 2.x, you need to extract the function 
from the wrapper. It is im_func or something like that. Use 
dir(B.createVars) to check for sure.

> How can I solve this problem?

Terry Jan Reedy

More information about the Python-list mailing list