How to bound a method to a instance ?
"Martin v. Löwis"
martin at v.loewis.de
Mon Feb 9 07:36:53 CET 2004
> main module :
> import toto
> a = toto.toto()
> a.method() -> does something ...
> reload (toto)
> now a is not reloaded...
> a.method = toto.toto().method
> does not work, because a.method would be bounded to a new instance...
It might be best to change the class of a:
a.__class__ = toto.toto
Then, a.method will automatically become the new method. Of course,
this will also change all other methods of toto, not just method.
If you really want to change only method, you could do
a.__class__.__dict__['method'] = toto.toto.__dict__['method']
That would change just method, but of all instances of the old
definition of toto.toto.
If you really want to change only one method, and only of one
object, you need to use new.instancemethod:
a.method = new.instancemethod(toto.toto.method.im_func, a, a.__class__)
More information about the Python-list