字符串的Python调用函数

que*_*sis 1 python python-2.7

s = "func"
Run Code Online (Sandbox Code Playgroud)

现在假设有一个称为func的函数。当函数名以字符串形式给出时,如何在Python 2.7中调用func?

Way*_*ner 6

最安全的方法是:

In [492]: def fun():
   .....:     print("Yep, I was called")
   .....:

In [493]: locals()['fun']()
Yep, I was called
Run Code Online (Sandbox Code Playgroud)

根据上下文,您可能要使用它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")
Run Code Online (Sandbox Code Playgroud)

您还可以将参数传递给函数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]()
Run Code Online (Sandbox Code Playgroud)