Python中的Python调用函数

本问题已经有最佳答案,请猛点这里访问。
1
s ="func"

现在假设有一个函数叫func。当函数名作为字符串给出时,我如何在Python 2.7中调用func ?


最安全的方法是:

1
2
3
4
5
6
In [492]: def fun():
   .....:     print("Yep, I was called")
   .....:

In [493]: locals()['fun']()
Yep, I was called

根据上下文的不同,您可能希望使用globals()

或者,你可能想要这样设置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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")

你也可以把参数传入你的函数a la:

1
2
3
4
5
6
7
8
9
10
11
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
2
3
4
5
6
7
8
9
def func():
    print("hello")
s ="func"
eval(s)()

In [7]: s ="func"

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

不推荐!只是告诉你怎么做。


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

1
2
3
s ="func()"

exec s

你可以通过传递一个字符串来执行一个函数:

1
exec(s + '()')