Functions are first-class objects in Python and can be assigned to class or instance attributes. One way to do the same as in the Wikipedia example:
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)
source share