gpt4 book ai didi

python - 通过字典访问函数

转载 作者:行者123 更新时间:2023-11-28 21:08:25 24 4
gpt4 key购买 nike

我有这样一个函数:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com