Allen a écrit :
[EMAIL PROTECTED] wrote:
On 26 juin, 17:18, Allen <[EMAIL PROTECTED]> 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.


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to