Injecting methods from one object to another

Eric Jacobs none at none
Fri Sep 1 19:22:29 EDT 2000


In article <wku2c00xlb.fsf at turangalila.harmonixmusic.com>, Dan Schmidt
<dfan at harmonixmusic.com> wrote:
> I want to copy method x from object foo to object bar.
> 
:
> 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.

That magic only happens if you lookup a function in a class through
an instance. 

Of course, if you know the arguments to the function, you can always
do

foo.x = lambda self=foo: bar.x.im_class.x.im_func(self)

But that won't work in the general case, because Python doesn't have
the form lambda *args, x=y. It also is not a genuine method object,
just a plain function.

The new module can create a genuine method object:

foo.x = new.instancemethod(bar.x.im_class.x.im_func, foo, foo.__class__)





More information about the Python-list mailing list