Dynamic class methods misunderstanding
Terry Reedy
tjreedy at udel.edu
Fri Jan 28 14:41:16 EST 2005
"Kamilche" <klachemin at comcast.net> wrote in message
news:1106928492.114459.191320 at c13g2000cwb.googlegroups.com...
>I see what you're attempting to do. However, your code, if it DID run,
> would result in a method being added to the object, not the object's
> class! Modify the class itself, not the object, as follows:
>
> |class Test:
> | def __init__(self):
> | self.method()
> |
> |def m(self):
> | print self
> |
> |setattr(Test, 'method', m)
# this is a longwinded way to say
Test.method = m
setattr is for when you do *not* know the attribute name at coding time but
will have it in a string at run time, as in
methodname = 'method'
......# some time later
setattr(Test, methodname, m)
Sometime Python makes things easier than people are initially willing to
believe ;-)
> |Test()
Terry J. Reedy
More information about the Python-list
mailing list