Dynamic class methods misunderstanding
Bill Mill
bill.mill at gmail.com
Fri Jan 28 15:00:57 EST 2005
On Fri, 28 Jan 2005 14:41:16 -0500, Terry Reedy <tjreedy at udel.edu> wrote:
>
> "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
That is the blindingly simple method that I wanted. I didn't know
before that I wanted it, but I'm sure of it now. Thank you very much,
terry.
>
> 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 ;-)
I felt like there had to be a simpler solution.
Peace
Bill Mill
bill.mill at gmail.com
More information about the Python-list
mailing list