Injecting methods from one object to another
Alex Martelli
aleaxit at yahoo.com
Fri Sep 1 17:50:30 EDT 2000
"Dan Schmidt" <dfan at harmonixmusic.com> wrote in message
news:wku2c00xlb.fsf at turangalila.harmonixmusic.com...
> I want to copy method x from object foo to object bar.
[snip]
> foo.x = bar.x
> doesn't work, because foo.x is still bound to bar:
Right, bar.x is a bound-method.
> The only problem is that foo.x is returning a function, not a method
> bound to foo. I thought that if x was a function member of foo, then
> foo.x would automatically bind it, but it's not.
The magical-morphing behaviour in question happens when you
assign a function to a _class_, but not when you assing it to an
_instance_.
> I'm sure that I'm almost there and that there's a very simple
> solution, but I can't find it. Anyone have the answer?
I think that's part of what the dreaded 'new' module lets you do:
class Bar:
def __init__(self):
self.who='Bar!'
def meth(self):
print "meth here",self.who
class Foo:
def __init__(self):
self.who='Foo!'
bar=Bar()
foo=Foo()
bar.meth()
import new
foo.meth=new.instancemethod(bar.meth.im_func,foo,Foo)
foo.meth()
Alex
More information about the Python-list
mailing list