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

marekw2143 mwawrzyczek at gmail.com
Fri Jul 24 04:35:52 EDT 2009


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
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?

Regards,
Marek



More information about the Python-list mailing list