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

Peter Otten __peter__ at web.de
Fri Jul 24 11:38:57 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).

You can move createVars() into a mixin or common base class:

class M(object):
    def createVars(self): ...

class A(M):
    ...

class B(M)
    ...

> When I try the folloowing:
> 
> 
> B.createVars = C.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)
> 
> When I try to add the createVars method to instance of B:
> 
>>>> b=B()
>>>> b.createVars = new.instancemethod(A.createVars, b, B)
>>>> b.createVars
> <bound method B.createVars of <__main__.B object at 0x7f6330cc4a90>>
>>>> b.createVars()
> 
> 
> 
> Then the following error raises:
> 
> 
> 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 B instance instead)
> 
> 
> 
> How can I solve this problem?

>>> class A(object):
...     def create_vars(self):
...             self.x = 42
...
>>> class B(object): pass
...
>>> B.create_vars = A.create_vars.im_func
>>> b = B()
>>> b.create_vars()
>>> b.x
42

An alternative I find a bit cleaner:

>>> def create_vars(self): self.x = 42
...
>>> class A(object):
...     create_vars = create_vars
...
>>> class B(object):
...     create_vars = create_vars
...
>>> b = B()
>>> b.create_vars()
>>> b.x
42

Peter





More information about the Python-list mailing list