Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's equivalent for Ruby's define_method?

Tags:

python

ruby

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)

like image 960
Rabarberski Avatar asked Dec 09 '22 09:12

Rabarberski


1 Answers

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)
like image 79
Sven Marnach Avatar answered Dec 27 '22 02:12

Sven Marnach