如何使用带有函数名称的字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
如何使用带有函数名称的字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
当前回答
虽然getattr()是一种优雅的(大约快7倍)方法,但您可以使用eval从函数(local、class方法、模块)获得返回值,其优雅程度与x=eval('fo.bar')()相同。当您实现一些错误处理时,就会非常安全(getattr也可以使用相同的原理)。模块导入和类示例:
# import module, call module function, pass parameters and print retured value with eval():
import random
bar = 'random.randint'
randint = eval(bar)(0,100)
print(randint) # will print random int from <0;100)
# also class method returning (or not) value(s) can be used with eval:
class Say:
def say(something='nothing'):
return something
bar = 'Say.say'
print(eval(bar)('nice to meet you too')) # will print 'nice to meet you'
当模块或类不存在(键入错误或其他更好的错误)时,就会引发NameError。如果函数不存在,则引发AttributeError。这可用于处理错误:
# try/except block can be used to catch both errors
try:
eval('Say.talk')() # raises AttributeError because function does not exist
eval('Says.say')() # raises NameError because the class does not exist
# or the same with getattr:
getattr(Say, 'talk')() # raises AttributeError
getattr(Says, 'say')() # raises NameError
except AttributeError:
# do domething or just...
print('Function does not exist')
except NameError:
# do domething or just...
print('Module does not exist')
其他回答
虽然getattr()是一种优雅的(大约快7倍)方法,但您可以使用eval从函数(local、class方法、模块)获得返回值,其优雅程度与x=eval('fo.bar')()相同。当您实现一些错误处理时,就会非常安全(getattr也可以使用相同的原理)。模块导入和类示例:
# import module, call module function, pass parameters and print retured value with eval():
import random
bar = 'random.randint'
randint = eval(bar)(0,100)
print(randint) # will print random int from <0;100)
# also class method returning (or not) value(s) can be used with eval:
class Say:
def say(something='nothing'):
return something
bar = 'Say.say'
print(eval(bar)('nice to meet you too')) # will print 'nice to meet you'
当模块或类不存在(键入错误或其他更好的错误)时,就会引发NameError。如果函数不存在,则引发AttributeError。这可用于处理错误:
# try/except block can be used to catch both errors
try:
eval('Say.talk')() # raises AttributeError because function does not exist
eval('Says.say')() # raises NameError because the class does not exist
# or the same with getattr:
getattr(Say, 'talk')() # raises AttributeError
getattr(Says, 'say')() # raises NameError
except AttributeError:
# do domething or just...
print('Function does not exist')
except NameError:
# do domething or just...
print('Module does not exist')
试试这个。虽然这仍然使用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)
根据Python编程常见问题解答,最好的答案是:
functions = {'myfoo': foo.bar}
mystring = 'myfoo'
if mystring in functions:
functions[mystring]()
这种技术的主要优点是字符串不需要与函数的名称匹配。这也是用于模拟案例构造的主要技术
这些建议对我都没有帮助。但我确实发现了这一点。
<object>.__getattribute__(<string name>)(<params>)
我使用的是python 2.66
希望这有帮助
答案(我希望)从来没有人想要
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")()