Injecting methods from one object to another
Dan Schmidt
dfan at harmonixmusic.com
Fri Sep 1 14:35:28 EDT 2000
I want to copy method x from object foo to object bar.
class Bar:
def __init__(self):
self.name = 'bar'
def x (self):
print self.name
class Foo:
def __init__(self):
self.name = 'foo'
bar = Bar()
foo = Foo()
Now,
foo.x = bar.x
doesn't work, because foo.x is still bound to bar:
>>foo.x()
bar
I want it to be bound to foo.
foo.x = bar.x
foo.x.im_self = foo
doesn't work, because im_self is read-only.
I tried to get the actual function Bar.x and bind it to foo by hand:
foo.x = bar.x.im_class.x.im_func
but that didn't work either:
>>foo.x()
TypeError: not enough arguments; expected 1, got 0
though it's close:
>>foo.x(foo)
foo
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.
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?
Thanks in advance.
--
Dan Schmidt | http://www.dfan.org
Honest Bob CD now available! | http://www.dfan.org/honestbob/cd.html
More information about the Python-list
mailing list