如何使用带有函数名称的字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
如何使用带有函数名称的字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
当前回答
给定一个字符串和一个函数的完整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()
其他回答
答案(我希望)从来没有人想要
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")()
在python3中,可以使用__getattribute__方法。请参见以下列表方法名称字符串示例:
func_name = 'reverse'
l = [1, 2, 3, 4]
print(l)
>> [1, 2, 3, 4]
l.__getattribute__(func_name)()
print(l)
>> [4, 3, 2, 1]
给定带有方法栏的模块foo:
import foo
bar = getattr(foo, 'bar')
result = bar()
getattr可以类似地用于类实例绑定方法、模块级方法、类方法。。。名单还在继续。
你的意思是从模块中获取指向内部函数的指针
import foo
method = foo.bar
executed = method(parameter)
这并不是一种更好的蟒蛇方式,对于准时的情况确实是可能的
这些建议对我都没有帮助。但我确实发现了这一点。
<object>.__getattribute__(<string name>)(<params>)
我使用的是python 2.66
希望这有帮助