Adding new methods at runtime to a class

Peter Otten __peter__ at web.de
Mon Nov 24 10:54:22 CET 2003


Fernando Rodriguez wrote:

> Hi,
> 
> How can I add new methods at runtime to a class?

Here's one dumb way to do it:

class Test(object):
    def __str__(self):
        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()
print t
Test.second = lambda self: "<SECOND>"
print t

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!

Peter




More information about the Python-list mailing list