如何使用函数名字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
如何使用函数名字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
假设有一个名为 foo
的模块,其中包含方法 bar
:
import foo
bar = getattr(foo, 'bar')
result = bar()
getattr
同样也可以用于类实例绑定的方法、模块级方法、类方法等,可谓是应用广泛。
foo
模块中,可以使用 globals()
来实现这个功能:methodToCall = globals()['bar']
。 - Ben Hoyt基于Patrick的解决方案,为了动态获取模块,可以使用以下导入方式:
module = __import__('foo')
func = getattr(module, 'bar')
func()
importlib.import_module
。官方文档对于__import__
说:“这是一个高级函数,不像importlib.import_module()
一样在日常Python编程中需要使用。”http://docs.python.org/2/library/functions.html#__import__ - glarrainimportlib.import_module
在 Python 3.6 中是被支持的。请看 https://docs.python.org/3.6/library/importlib.html#importlib.import_module。 - cowlinatorfoo.bar.module
,__input__
仅导入基本模块 foo
,而 importlib.import_module
返回 foo.bar.module
。使用 foo/bar/module
,__import__
返回预期的模块。 - Conner M.仅做一点简单的贡献。如果我们需要实例化的类与当前文件相同,可以使用以下代码:
# Get class from globals and create an instance
m = globals()['our_class']()
# Get the function (from the instance) that we need to call
func = getattr(m, 'function_name')
# Call it
func()
例如:class A:
def __init__(self):
pass
def sampleFunc(self, arg):
print('you called sampleFunc({})'.format(arg))
m = globals()['A']()
func = getattr(m, 'sampleFunc')
func('sample arg')
# Sample, all on one line
getattr(globals()['A'](), 'sampleFunc')('sample arg')
如果不是一个类:
def sampleFunc(arg):
print('you called sampleFunc({})'.format(arg))
globals()['sampleFunc']('sample arg')
给定一个字符串,其中包含完整的Python函数路径,以下是我获取该函数结果的方法:
import importlib
function_string = 'mypackage.mymodule.myfunc'
mod_name, func_name = function_string.rsplit('.',1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
result = func()
__import__
函数的轻量级版本。 - Pankaj Bhambhani根据Python编程FAQ,最佳答案是:
functions = {'myfoo': foo.bar}
mystring = 'myfoo'
if mystring in functions:
functions[mystring]()
希望没有人需要的答案
类似eval的行为
getattr(locals().get("foo") or globals().get("foo"), "bar")()
为什么不添加自动导入?
getattr(
locals().get("foo") or
globals().get("foo") or
__import__("foo"),
"bar")()
如果我们有额外的字典需要检查
getattr(next((x for x in (f("foo") for f in
[locals().get, globals().get,
self.__dict__.get, __import__])
if x)),
"bar")()
我们需要深入
getattr(next((x for x in (f("foo") for f in
([locals().get, globals().get, self.__dict__.get] +
[d.get for d in (list(dd.values()) for dd in
[locals(),globals(),self.__dict__]
if isinstance(dd,dict))
if isinstance(d,dict)] +
[__import__]))
if x)),
"bar")()
试试这个。虽然这仍然使用eval,但它只是用它来从当前上下文中召唤函数。然后,您就有了真正的函数可以根据自己的需要使用。
对我来说主要的好处是,在召唤函数时会得到任何与eval相关的错误。然后在调用函数时,您将只得到与函数相关的错误。
def say_hello(name):
print 'Hello {}!'.format(name)
# get the function by name
method_name = 'say_hello'
method = eval(method_name)
# call it like a regular function later
args = ['friend']
kwargs = {}
method(*args, **kwargs)
eval
。在这种情况下,getattr(__module__, method_name)
是更好的选择。 - moi如果你需要将函数(或类)名称和应用程序名称作为字符串传递,可以这样做:
myFnName = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn = getattr(app,myFnName)
handler = getattr(sys.modules[__name__], myFnName)
。 - lony作为这个问题的重复,如何使用方法名称分配调用类中的方法,我在这里发布一个相关的答案:
情况是,在类中的一个方法想要动态地调用同一类中的另一个方法,我已经添加了一些细节到原始示例,提供了一些更广泛的场景和清晰度:
class MyClass:
def __init__(self, i):
self.i = i
def get(self):
func = getattr(MyClass, 'function{}'.format(self.i))
func(self, 12) # This one will work
# self.func(12) # But this does NOT work.
def function1(self, p1):
print('function1: {}'.format(p1))
# do other stuff
def function2(self, p1):
print('function2: {}'.format(p1))
# do other stuff
if __name__ == "__main__":
class1 = MyClass(1)
class1.get()
class2 = MyClass(2)
class2.get()
输出(Python 3.7.x)
function1:12
function2:12