Python Call Function from String
This question already has an answer here:
you could use exec. Not recommended but doable.
s = "func()"
exec s
def func():
print("hello")
s = "func"
eval(s)()
In [7]: s = "func"
In [8]: eval(s)()
hello
Not recommended! Just showing you how.
The safest way to do this:
In [492]: def fun():
.....: print("Yep, I was called")
.....:
In [493]: locals()['fun']()
Yep, I was called
Depending on the context you might want to use globals()
instead.
Alternatively you might want to setup something like this:
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")
You can also pass arguments into your function a 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/55166.html
上一篇: 从Python中存储的字符串调用函数
下一篇: 来自字符串的Python调用函数