Adding functions to an existing instance

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Jun 27 04:28:06 EDT 2008


Allen a écrit :
> 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 

Indeed, since this is how bound methods are created anyway.

> 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.

Yes, true. I suppose you have good reasons to worry about cyclic 
references here, but I fail to imagine what they are.

Another solution might be to create new class on the fly from the 
instance's class, inserting the function in the attribs dict, and then 
rebind the instance's __class__ to this new class, but that might be a 
bit overkill.





More information about the Python-list mailing list