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

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

那就是:

obj = MyClass() # this class has a method doStuff()
func = "doStuff"
# how to call obj.doStuff() using the func variable?
55626 次浏览

使用 getattr内置函数

obj = MyClass()
try:
func = getattr(obj, "dostuff")
func()
except AttributeError:
print("dostuff not found")