Python - 如何通过名称动态调用对象上的函数?

Roy*_*ang 45 python

在python中,假设我有一个字符串,其中包含我知道特定对象将具有的类函数的名称,如何调用它?

那是:

obj = MyClass() # this class has a method doStuff()
func = "doStuff"
# how to call obj.doStuff() using the func variable?
Run Code Online (Sandbox Code Playgroud)

Ada*_*erg 62

使用"getattr":http://docs.python.org/library/functions.html?highlight = getattr #getattr

obj = MyClass()
try:
    func = getattr(obj, "dostuff")
    func()
except AttributeError:
    print "dostuff not found"
Run Code Online (Sandbox Code Playgroud)

  • 此链接还有上述问题的有用且重要的示例https://gist.github.com/hygull/41f94e64b84f96fa01d04567e27eb46b (2认同)