Adding new methods at runtime to a class
__peter__ at web.de
Mon Nov 24 10:54:22 CET 2003
Fernando Rodriguez wrote:
> How can I add new methods at runtime to a class?
Here's one dumb way to do it:
return self.first() + self.second() + self.third()
for m in "first second third".split():
setattr(Test, m, lambda self, name=m: "<%s>" % name)
t = Test()
Test.second = lambda self: "<SECOND>"
The obvious question: why do you want to do it?
The question you didn't ask: Is there a better way to solve my problem
(whatever that may be)
The most likely answer: YES!
More information about the Python-list