通过字典访问功能 [英] Access Functions via Dictionary
问题描述
def abc(a,b):
return a + b
我想将它分配到这样的字典中:
functions = {'abc':abc(a,b)}
问题在于,将它分配给字典时,由于参数尚未定义,所以我收到错误消息:
NameError:名称'a'未定义
我会做显而易见的事情并提前定义参数,但我需要在一个循环中定义它们(然后根据定位它在列表中调用该函数),如下所示:
functions_to_call = ['abc']
for function_to_call:
a = 3
b = 4
#这应该是定位并运行函数该字典是否在函数列表中。
if f函数:
函数[f]
$ b $
我需要在一个循环中定义它们(然后根据定位它在列表中调用该函数) b
然后,简单地将函数对象保存在字典中有什么问题:
functions = {' abc':abc}
和然后应用一个
和 b
给函数while循环:
<$ c
$ b $ 3,4
如果函数中有f:
函数[f](a,b) )
I have a function like this:
def abc(a,b):
return a+b
And I want to assign it to a dictionary like this:
functions = {'abc': abc(a,b)}
The trouble is, when assigning it to the dictionary, since the arguments are not yet defined, I get the error:
NameError: name 'a' is not defined
I would do the obvious thing and define the arguments ahead of time but I need to define them in a loop (and then call the function based on locating it in a list) like this:
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)
Then what's the issue with simply saving the function object in the dictionary:
functions = {'abc':abc}
and then applying a
and b
to the function while looping:
functions_to_call = ['abc']
for f in functions_to_call:
a, b = 3, 4
if f in functions:
functions[f](a, b)
这篇关于通过字典访问功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!