作为this question的后续行动: 我有两个看起来像这样的函数:
def abc(a,b):
return a+b
def cde(c,d):
return c+d
我想把它分配到这样的字典:
functions = {'abc': abc(a,b), 'cde': cde(c,d)}
我可以这样做,但它会在' cde'
中断functions = {'abc':abc, 'cde':cde}
functions_to_call = ['abc', 'cde']
for f in functions_to_call:
a, b = 3, 4
c, d = 1, 2
if f in functions:
functions[f](a, b)
另外,如果cde有3个参数怎么办?
答案 0 :(得分:2)
制作一个单独的args
序列并使用splat运算符(*
):
>>> def ab(a,b):
... return a + b
...
>>> def cde(c,d,e):
... return c + d + e
...
>>> funcs = {'ab':ab, 'cde':cde}
>>> to_call = ['ab','cde']
>>> args = [(1,2),(3,4,5)]
>>> for fs, arg in zip(to_call,args):
... print(funcs[fs](*arg))
...
3
12