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

27 浏览
0 Comments

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

这个问题在这里已经有了答案:

使用字符串调用模块的函数

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

也就是说:

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

admin 更改状态以发布 2023年5月19日
0
0 Comments

使用内置函数 getattr。请参阅文档

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

0