Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #24629
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: moving methods from class to instance of other class |
| Date | 2012-06-28 13:57 -0400 |
| References | <c376d4cf-c888-4fa9-8d4c-032b80a43947@e20g2000vbm.googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1616.1340906279.4697.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
moving methods from class to instance of other class lars van gemerden <lars@rational-it.com> - 2012-06-27 23:59 -0700
Re: moving methods from class to instance of other class Benjamin Kaplan <benjamin.kaplan@case.edu> - 2012-06-28 00:22 -0700
Re: moving methods from class to instance of other class lars van gemerden <lars@rational-it.com> - 2012-06-28 01:14 -0700
Re: moving methods from class to instance of other class Terry Reedy <tjreedy@udel.edu> - 2012-06-28 13:57 -0400
Re: moving methods from class to instance of other class Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2012-06-28 14:15 -0400
csiph-web