Rabarberski
Rabarberski

Reputation: 24922

Python's equivalent for Ruby's define_method?

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)

Upvotes: 6

Views: 1100

Answers (3)

Sven Marnach
Sven Marnach

Reputation: 601779

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)

Upvotes: 14

9000
9000

Reputation: 40894

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

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363607

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.

Upvotes: 2

Related Questions