Python's equivalent for Ruby's define_method?

后端 未结 4 1993
傲寒
傲寒 2021-01-06 10:57

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

4条回答
  •  隐瞒了意图╮
    2021-01-06 11:28

    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 '%s' % (code, self)
        setattr(MyString, "in_" + name, _in_colour)
    

提交回复
热议问题