我有这样一个函数:
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]
最佳答案
I need to define them in a loop (and then call the function based on locating it in a list)
那么简单地将函数对象保存在字典中有什么问题:
functions = {'abc':abc}
和然后在循环时将a
和b
应用于函数:
functions_to_call = ['abc']
for f in functions_to_call:
a, b = 3, 4
if f in functions:
functions[f](a, b)
关于python - 通过字典访问函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39926137/