moving methods from class to instance of other class

lars van gemerden lars at rational-it.com
Thu Jun 28 02:59:22 EDT 2012


Hi all,

I have some trouble with the following question: Let say i have the
following classes:

class A(object):
    def __init__(self):
        self.name = 'a'
    def do(self):
        print 'A.do: self.name =', self.name

class B(object):
    def __init__(self):
        self.name = 'b'



The question is: How do i move the 'do' method from A to b (resulting
in  printing "A.do: self.name = b")?

I have tried (with a = A() and b  B()):

B.do = types.MethodType(A.do, b) #Error

and stuff like:

b.do = a.do
b.do()

But either i get an error or b.do() prints  "A.do: self.name = a", so
the self parameter of a.do is stored somehow in the method.

In other words, how do i unbind 'do' from a/A and bind it to b (the
instance)?

Cheers, Lars







More information about the Python-list mailing list