python - 通过字典访问函数

标签 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] 

最佳答案

I need to define them in a loop (and then call the function based on locating it in a list)

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

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)

关于python - 通过字典访问函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39926137/

相关文章:

c++ - C++ 中的链表排序

python - 将项目插入字典的中间

python - 为什么这个 dos 命令在 python 中不起作用?

python - 在python中重命名多个文件

Python从字典中删除 'duplicate'元组

python - python 列表中的组合

c - 将一个字符串复制到另一个字符串的程序(包含该函数)正在打印奇怪的字符

javascript - 删除并重新添加函数 javascript?

function - 如果条件以另一种/更好的方式?

python - 将 pandas 时间序列加入日期范围