如何从列表中调用函数?

Lui*_*ipe 2 python function

例如,我有以下列表:

method = [fun1, fun2, fun3, fun4]
Run Code Online (Sandbox Code Playgroud)

然后我显示一个菜单,用户必须从1-4(len(method))中选择一个数字.如果用户选择i,我必须使用该功能funi.我怎样才能做到这一点?

例如.

A=['hello','bye','goodbye']
def hello(n):
 print n**2
def bye(n):
 print n**3
def goodbye(n):
 print n**4
Run Code Online (Sandbox Code Playgroud)

如果我想bye通过数组A 调用该函数,请使用

>>>A[1](7)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
A[2](5)
TypeError: 'str' object is not callable
Run Code Online (Sandbox Code Playgroud)

如何使用保存的名称A来调用我的函数?因为每个方法都保存在一个字符串中.

Tas*_*lou 8

让我们来看看...

你可以使用parens()来调用函数fn fn()

您可以通过索引运算符[]访问列表中的项目,如下所示 lst[idx]

所以,将两者结合起来 lst[idx](*args)

编辑

Python列表索引从零开始,因此第一项为0,第二项为1等等......如果用户选择1-4,则必须减去一项.

编辑

鉴于澄清,可以进行以下操作

def method1():
    pass

def method2():
    pass


methods = [method1, method2]
Run Code Online (Sandbox Code Playgroud)

你可以使用上面的逻辑.通过这种方式,您不必将实际函数名称的字符串实际解析为实际函数.

请记住,python中的函数是第一类,因此您可以将它们的引用存储到列表中(我们methods=[]在线执行的操作)