来自字符串的Python调用函数
这个问题在这里已经有了答案:
你可以使用exec。 不推荐,但可行。
s = "func()"
exec s
def func():
print("hello")
s = "func"
eval(s)()
In [7]: s = "func"
In [8]: eval(s)()
hello
不建议! 只是告诉你如何。
最安全的方法是:
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]()
链接地址: http://www.djcxy.com/p/55165.html
上一篇: Python Call Function from String
下一篇: How do I use user input to invoke a function in Python?