python - 如何以编程方式创建对象方法?

标签 python

是否可以在 python 中以编程方式创建对象方法?

由于使用命令行解析器的现有结构,我需要任意数量 (N) 的方法,其中 (N) 是在运行时建立的。

def activatetool_>N<():
  print 'activating tool number: >N<'

我设法接近了:

class TestClass:
    def __init__(self, toolcount):
        for i in range(toolcount):
            exec('def activatetool_{}(): print \'activating tool {}\''.format(i,i)) in globals()

然而,这定义了全局函数,而不是类方法。通过设计我正在使用的现有代码,我需要能够以以下形式调用它们:

obj=TestClass(5)
obj.activatetool3()
obj.activatetool1()

澄清:由于我正在使用的现有解析器的结构,重构为 obj.activatetool(N) 形式的解决方案不可行。

最佳答案

Python 方法只是类的一个属性,它恰好是一个接受类实例作为其第一个参数的函数。因此,您可以只使用 setattr 将新方法绑定(bind)到现有类。

根据您的示例,您可以创建一个函数来添加工具:

def addTool(cls, n):
    def tool(self):
        print ('activating tool number >{}<'.format(n))
    setattr(cls, "activatetool{}".format(n), tool)

然后您可以创建一个类,它的一个实例,添加一个工具并成功地使用该工具:

class TestClass:
    pass
t = TestClass()
addTool(TestClass, 3)
t.activatetool3()

你得到了预期的结果:

activating tool number >3<

Python 的神奇之处在于,由于动态方法是类的属性,所以类的所有实例都可以访问它,即使它们是在添加方法之前创建的。

关于python - 如何以编程方式创建对象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43234999/

相关文章:

python - ThreadPoolExecutor 未定义 [python3]

python - Plone:从 plone 页面调用外部 python 脚本

python - 使用 Raspberry Pi Python SMBus 乱序接收 I²C 字节

python - 在 Python 中读取和覆盖文件

python - 将结果限制为 django 和 mezzanine 的最新结果

python - python 中的字符串连接发生在下一行

python - 在 numpy 3D 数组中查找值索引

python - 在 Python 中求多项式的导数

python - python 打印非字母 ASCII 字符的奇怪行为

python - 如何使用用户、文本数据调用 MultinomialNB.predict()?