如何通过名称动态调用对象上的函数?
在Python中,假设我有一个字符串,这个字符串包含了一个类函数的名字,而我知道某个特定的对象会有这个函数,我该怎么调用它呢?
也就是说:
obj = MyClass() # this class has a method doStuff()
func = "doStuff"
# how to call obj.doStuff() using the func variable?
1 个回答
111
使用内置的 getattr
函数。你可以查看这个 文档 来了解更多信息。
obj = MyClass()
try:
func = getattr(obj, "dostuff")
func()
except AttributeError:
print("dostuff not found")