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
In Python, you can just set a method on a class:
>>> class Spam:
... def __init__(self, x):
... self.value = x
...
>>> Spam.getvalue = lambda self: self.value
>>> ham = Spam('ham')
>>> ham.getvalue()
'ham'
Fancier stuff is possible with decorators.
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
Functions are first-class objects in Python and can be assigned to attributes of a class or an instance. One way to do the same thing as in the Wikipedia example is:
colours = {"black": "000",
"red": "f00",
"green": "0f0",
"yellow": "ff0",
"blue": "00f",
"magenta": "f0f",
"cyan": "0ff",
"white": "fff"}
class MyString(str):
pass
for name, code in colours.iteritems():
def _in_colour(self, code=code):
return '<span style="color: %s">%s</span>' % (code, self)
setattr(MyString, "in_" + name, _in_colour)
Either look into abstract base classes:
http://docs.python.org/library/abc.html
or
check the options that the 'new' (or the newer 'types') module provides to you.