Adding functions to an existing instance

Allen brian_vanderburg2 at yahoo.com
Thu Jun 26 19:23:11 EDT 2008


bruno.desthuilliers at gmail.com wrote:
> On 26 juin, 17:18, Allen <brian_vanderbu... at yahoo.com> wrote:
>> I need a way to add a method to an existing instance, but be as close as
>> possible to normal instance methods.
> 
> def set_method(obj, func, name=None):
>   if not name:
>     name = func.__name__
>   setattr(obj, name, func.__get__(obj, type(obj)))
> 
> class Toto(object):
>   pass
> 
> toto = Toto()
> 
> def titi(self):
>   print self
> 
> set_method(toto, titi)
> 

I tried that.  func.__get__(obj, type(obj)) creates a bound method and 
then sets an attribute to that, creating a cyclic reference.  toto 
contains a reference to the bound method, the bound method contains a 
reference to the instance toto.

However it does eliminate the need for FunctionCaller.  Instead of:

	return InstanceFunctionHelper.FunctionCaller(self, funcs[name])

__getattr__(...) can just do:

	return funcs[name].__get__(self, type(self))

to get the same behavior.

All of the extra __setattr__ and __delattr__ exist so that if the 
attribute is set after a function is set, it will delete the function so 
that later deleting the attribute will not make the function visible again.


Brian Vanderburg II



More information about the Python-list mailing list