通过字典访问功能

时间:2016-10-07 21:35:09

标签: python list function python-3.x dictionary

我有这样的功能:

def abc(a,b):
    return a+b

我想把它分配到这样的字典:

functions = {'abc': abc(a,b)}

麻烦的是,在将它分配给字典时,由于参数尚未定义,我得到错误:

NameError: name 'a' is not defined

我会做一件显而易见的事情并提前定义参数但是我需要在循环中定义它们(然后根据它在列表中定位来调用函数),如下所示:

functions_to_call = ['abc']
for f in functions_to_call:
    a=3
    b=4
#This is supposed to locate and run the function from the dictionary if it is in the list of functions.
    if f in functions:
       functions[f] 

2 个答案:

答案 0 :(得分:3)

  

我需要在循环中定义它们(然后根据在列表中定位它来调用函数)

那么简单地将函数对象保存在字典中会出现什么问题:

functions = {'abc':abc}

然后在循环时将ab应用于该函数:

functions_to_call = ['abc']
for f in functions_to_call:
    a, b = 3, 4
    if f in functions:
       functions[f](a, b)

答案 1 :(得分:3)

您可以为函数指定一个引用,不带任何参数,然后在调用它时提供它们:

functions = {'abc':abc} # Assignment: no arguments!
functions_to_call = ['abc']
for f in functions_to_call:
    a=3
    b=4
    if f in functions:
            functions[f](a, b) # calling with arguments