Is there a Python equivalent for Ruby\'s define_method
, which would allow dynamic generation of class methods?
(as can be seen in Wikipedia\'s Ruby example code
You just assign a function as a new attribute to a class:
def replacement_method(self):
print self.name
class Foo(object):
def __init__(self, name):
self.name = name
# .... whatever
setattr(Foo, "printMyName", replacement_method) # assign it
Foo("Joe").printMyName() # call it
If you don't need a computable name (as are strings in the sample from Wikipedia), you can have it even cleaner:
Foo.printMyName = replacement_method