是否有一种方法可以将函数存储在列表或字典中,以便在调用索引(或键)时触发存储的函数?

例如,我试过像 mydict = {'funcList1': [foo(),bar(),goo()], 'funcList2': [foo(),goo(),bar()]这样的东西,但是没有用。

是否存在某种具有这种功能的结构?

我意识到,我显然可以用一堆 def语句轻松地做到这一点:

def func1():
foo()
bar()
goo()

但是我需要的陈述的数量正变得相当笨重和难以记住。如果能把它们很好地包装在一本字典中,我就可以时不时地检查它们的键。

91918 次浏览

函数是 Python 中的第一类对象,因此可以使用 dictionary 进行分派。例如,如果 foobar是函数,而 dispatcher是这样的字典。

dispatcher = {'foo': foo, 'bar': bar}

注意,这些值是函数对象 foobar,而不是 foo()bar()

要调用 foo,只需调用 dispatcher['foo']()即可

编辑: 如果您想运行存储在列表中的 多个函数,您可以这样做。

dispatcher = {'foobar': [foo, bar], 'bazcat': [baz, cat]}


def fire_all(func_list):
for f in func_list:
f()


fire_all(dispatcher['foobar'])
# Lets say you have 10 programs or functions:
func_list = [program_001, program_002, program_003, program_004, program_005,
program_006, program_007, program_008, program_009, program_010]


choose_program = int(input('Please Choose a program: ')) # input function number


func_list[choose_program - 1]()