Adding method at runtime - problem with self

Jay Parlar jparlar at cogeco.ca
Mon Mar 6 02:41:59 CET 2006


On Mar 5, 2006, at 2:30 PM, Marek wrote:

> Assume I want to add a method to an object at runtime. Yes, to an
> object, not a class - because changing a class would have global
> effects and I want to alter a particular object only. The following
> approach fails:
>
> class kla:
>     x = 1
>
> def foo(self):
>     print self.x
>
> k = kla()
> k.foo = foo
> k.foo()
>
> I know where the problem is. The method shouldn't have 'self'
> parameter. But how do I access object's attributes without it?
>
> Best regards,
>
> Marek
>

First off, it should be 'class kla(object)', but that's minor.

Try this:

import types

class kla(object):
     x = 1

def foo(self):
     print self.x

k = kla()
k.foo = types.MethodType(foo,k) #Makes 'foo' an instancemethod
k.foo()


Jay P.




More information about the Python-list mailing list