在Python程序中,给定带有函数名称的字符串的最佳方法是什么? 例如,假设我有一个模块foo
,而且我有一个字符串,其内容为"bar"
。 调用foo.bar()
的最佳方法是什么? html
我须要获取函数的返回值,这就是为何我不仅是使用eval
。 我想出了如何经过使用eval
定义一个返回该函数调用结果的temp函数来执行此操做的方法,但我但愿有一种更优雅的方法来执行此操做。 python
只是一个简单的贡献。 若是咱们须要实例化的类在同一文件中,则能够使用相似如下内容的东西: 函数
# 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()
例如: spa
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')
并且,若是不是课程: code
def sampleFunc(arg): print('you called sampleFunc({})'.format(arg)) globals()['sampleFunc']('sample arg')
建议的内容都没有帮助我。 我确实发现了这一点。 orm
<object>.__getattribute__(<string name>)(<params>)
我正在使用python 2.66 htm
但愿这能够帮助 字符串
给定一个字符串,带有指向函数的完整python路径,这就是我如何获取所述函数的结果: get
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()
答案(我但愿)没有人想要 string
评估行为
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")()
假设模块foo
与方法bar
:
import foo method_to_call = getattr(foo, 'bar') result = method_to_call()
您能够将第2行和第3行缩短为:
result = getattr(foo, 'bar')()
若是这对您的用例更有意义。
您能够经过这种方式在类实例绑定的方法,模块级方法,类方法上使用getattr
...清单继续。