adding methods at runtime

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Jan 11 12:00:44 CET 2008


zslevi at gmail.com a écrit :
> Can I access the class attributes from a method added at runtime? 

Of course.

> (My
> experience says no.)

So there's something wrong with your experience !-)

> I experimented with the following code:
> 
> 
> class myclass(object):
>     myattr = "myattr"
> 
> instance = myclass()
> def method(x):
>     print x
> 
> instance.method = method

As Marc pointed out, you're not adding a method but a function. What you 
want is:

def method(self, x):
   print "x : %s - myattr : %s" % (x, self.myattr)

import new
instance.method = new.instancemethod(method, instance, myclass)

Note that this is only needed for per-instance methods - if you want to 
add a new method for all instances, you just set the function as 
attribute of the class. The lookup mechanism will then invoke the 
descriptor protocol on the function object, which will return a method 
(FWIW, you have to do it manually on per-instance methods because the 
descriptor protocol is not invoked on instance attributes, only on class 
attributes).

HTH



More information about the Python-list mailing list