Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #24596

Re: moving methods from class to instance of other class

References <c376d4cf-c888-4fa9-8d4c-032b80a43947@e20g2000vbm.googlegroups.com>
Date 2012-06-28 00:22 -0700
Subject Re: moving methods from class to instance of other class
From Benjamin Kaplan <benjamin.kaplan@case.edu>
Newsgroups comp.lang.python
Message-ID <mailman.1590.1340868149.4697.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Jun 27, 2012 at 11:59 PM, lars van gemerden
<lars@rational-it.com> wrote:
> 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
>

Is there any particular reason you can't just have B be a subclass of
A? You could do

b.do = types.MethodType(A.do.im_func, b, B)

but there's no point in re-inventing the wheel.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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