Adding new methods at runtime to a class

P

Peter Otten

Fernando said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top