s = "func"
现在假设有一个名为func的函数。 当函数名以字符串形式给出时,如何在Python 2.7中调用func?
答案 0 :(得分:4)
最安全的方法:
In [492]: def fun():
.....: print("Yep, I was called")
.....:
In [493]: locals()['fun']()
Yep, I was called
根据您可能需要使用globals()
的上下文。
或者你可能想要设置这样的东西:
def spam():
print("spam spam spam spam spam on eggs")
def voom():
print("four million volts")
def flesh_wound():
print("'Tis but a scratch")
functions = {'spam': spam,
'voom': voom,
'something completely different': flesh_wound,
}
try:
functions[raw_input("What function should I call?")]()
except KeyError:
print("I'm sorry, I don't know that function")
你也可以将参数传递给你的函数la:
def knights_who_say(saying):
print("We are the knights who say {}".format(saying))
functions['knights_who_say'] = knights_who_say
function = raw_input("What is your function? ")
if function == 'knights_who_say':
saying = raw_input("What is your saying? ")
functions[function](saying)
else:
functions[function]()
答案 1 :(得分:1)
你可以使用exec。不推荐但可行。
s = "func()"
exec s
答案 2 :(得分:1)
def func():
print("hello")
s = "func"
eval(s)()
In [7]: s = "func"
In [8]: eval(s)()
hello
不推荐!只是告诉你如何。
答案 3 :(得分:0)
您可以通过传递字符串来执行函数:
exec(s + '()')