Python 相当于 Ruby 的define_method? [英] Python's equivalent for Ruby's define_method?

查看:50
本文介绍了Python 相当于 Ruby 的define_method?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有与 Ruby 的 define_method 等效的 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)

推荐答案

函数是 Python 中的第一类对象,可以分配给类或实例的属性.执行与维基百科示例相同的事情的一种方法是:

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)

这篇关于Python 相当于 Ruby 的define_method?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆