moving methods from class to instance of other class
Terry Reedy
tjreedy at udel.edu
Thu Jun 28 13:57:25 EDT 2012
On 6/28/2012 2:59 AM, lars van gemerden wrote:
> 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")?
If you want to move the method from class A to class B
(which is normally more sensible than to instance b of B)
B.do = A.do.im_func # Python 2
B.do = A.do # Python 3
b = B()
b.do()
# print (with print adjusted for PY3)
A.do: self.name = b
If you want a B instance to act like an A instance, you can change its
class (subject to some limitations). The following works.
b = B()
b.__class__ = A
b.do()
If make the change temporary and the reversion automatic, write a
context manager.
--
Terry Jan Reedy
More information about the Python-list
mailing list