如何通过索引选择调用函数

How to call functions through an index selection

我想知道是否可以存储然后调用函数,就像您从列表中调用索引项一样?

在下面的代码中,x 表示我尚未确定为该程序中最终函数的索引号。稍后,我将添加代码以使用其索引函数打印列表,但现在我想让这个程序运行。索引 0 标记为空白,因为输入零可能会使某些用户感到困惑。

我说的相关代码:

print("Weights and Measurements will convert the Imperial measurments, into the corresponding metric measurement.")

programSelect = eval(input("Please choose a program from the list below, with its corresponding index number (1-x):" ))
programs = ["blank", "def tempConvert", "def distance"]

这个想法是让用户通过索引号 select 函数。我不知道如何激活各个功能,如 def tempConvert 或 def distance 并显示它们相应的菜单。

这样想。

命令提示符将显示为

"Weights and Measurements will convert the Imperial measurments, into the corresponding metric measurement."

"Please choose a program from the list below, with its corresponding index number (1-x):"

假设我输入 1 到 select def tempConvert 函数

然后它会显示 def tempConvert 函数的以下内容

"Please use either Celsius or Fahrenheit" "Please enter a temperature for Celsius: " "Please enter a temperature for Fahrenheit: "

我知道我需要处理个别程序,以防止用户同时输入摄氏度和华氏度温度。现在,该程序可以独立运行,但我希望它可以在更大的程序中运行。

是的,这很容易做到:

def function1():
    print "hi, I'm function1"
def function2():
    print "hi, I'm function2"
list_of_functions = [function1, function2]
....
list_of_functions[x]() # this calls the function at index x

注意调用的函数是function1,不是"def function1";每个函数都是 python 中的对象,并且可以存储在列表、字典或变量中,就像您可以存储整数、字符串或您自己的 class 实例一样。