【发布时间】:2015-04-19 14:54:56
【问题描述】:
我将如何执行以下操作:
instance.method()
我知道我可以通过 getattr(instance, method) 获取 instance.method,但是是否有一个内置函数可以实际运行该方法?
【问题讨论】:
标签: python
我将如何执行以下操作:
instance.method()
我知道我可以通过 getattr(instance, method) 获取 instance.method,但是是否有一个内置函数可以实际运行该方法?
【问题讨论】:
标签: python
只需getattr(instance, method)()。 getattr 返回方法对象,您可以像任何其他可调用对象一样使用 () 调用它。
【讨论】:
您只需在末尾添加一个():
getattr(instance,method)()
【讨论】:
您可以使用operator.methodcaller 创建一个函数,该函数将在执行时在传递的实例上运行该方法。但是,您仍然必须在实例上实际调用它。
from operator import methodcaller
call_hello = methodcaller('hello', 'Jack')
call_hello(something) # same as something.hello('Jack')
当您想在不同的实例上调用相同的方法但您不知道其名称时,这很有用。
【讨论】: