Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python从字符串调用函数_Python_Python 2.7 - Fatal编程技术网

Python从字符串调用函数

Python从字符串调用函数,python,python-2.7,Python,Python 2.7,现在假设有一个名为func的函数。 当函数名以字符串形式给出时,如何在Python 2.7中调用call func?可以使用exec。不推荐,但可行 s = "func" 不推荐只是演示如何执行。您可以通过传递字符串来执行函数: def func(): print("hello") s = "func" eval(s)() In [7]: s = "func" In [8]: eval(s)() hello 最安全的方法是: exec(s + '()') 根据上下文,您可能希望

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

可以使用exec。不推荐,但可行

s = "func"

不推荐只是演示如何执行。

您可以通过传递字符串来执行函数:

def func():
    print("hello")
s = "func"
eval(s)()

In [7]: s = "func"

In [8]: eval(s)()
hello

最安全的方法是:

exec(s + '()')
根据上下文,您可能希望改用
globals()

或者,您可能希望设置如下内容:

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

In [493]: locals()['fun']()
Yep, I was called
您还可以将参数传递到函数a la中:

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")

@巴尔加夫罗,这是一个大胆的声明@洋红新星,我很确定does@padriac,您是对的,删除注释。这不会起作用,因为您从未调用函数。是的,我知道,它只会返回函数对象,而不会调用它。我修好了。
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")
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]()