使用模块名称(字符串)调用模块的函数 [英] Calling a function of a module by using its name (a string)
问题描述
在 Python 程序中调用具有函数名称的字符串的函数的最佳方法是什么.例如,假设我有一个模块 foo
,我有一个内容为 "bar"
的字符串.调用 foo.bar()
的最佳方式是什么?
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo
, and I have a string whose content is "bar"
. What is the best way to call foo.bar()
?
我需要获取函数的返回值,这就是为什么我不只是使用eval
.我想出了如何通过使用 eval
定义一个临时函数来返回该函数调用的结果,但我希望有一种更优雅的方法来做到这一点.
I need to get the return value of the function, which is why I don't just use eval
. I figured out how to do it by using eval
to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
推荐答案
假设模块 foo
和方法 bar
:
Assuming module foo
with method bar
:
import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()
您可以将第 2 行和第 3 行缩短为:
You could shorten lines 2 and 3 to:
result = getattr(foo, 'bar')()
如果这对您的用例更有意义.
if that makes more sense for your use case.
您可以以这种方式使用 getattr
类实例绑定方法、模块级方法、类方法……不胜枚举.
You can use getattr
in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.
这篇关于使用模块名称(字符串)调用模块的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!