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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3951840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:31:37  来源:igfitidea点击:

How to invoke a function on an object dynamically by name?

python

提问by Roy Tang

In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it?

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

That is:

那是:

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

采纳答案by Adam Vandenberg

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

使用“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"