def f1(n): #accepts one argument
pass
def f2(): #accepts no arguments
pass
FUNCTION_LIST = [(f1,(2)), #each list entry is a tuple containing a function object and a tuple of arguments
(f1,(6)),
(f2,())]
for f, arg in FUNCTION_LIST:
f(arg)
在循环的第三次循环中,它尝试将空的参数元组传递给不接受参数的函数。它给出错误TypeError: f2() takes no arguments (1 given)。前两个函数调用工作正常-传递元组的内容,而不是元组本身。在
删除有问题的列表项中的空参数元组并不能解决问题:
^{pr2}$
结果是ValueError: need more than 1 value to unpack。在
我还尝试迭代索引而不是列表元素。在for n in range(len(FUNCTION_LIST)):
FUNCTION_LIST[n][0](FUNCTION_LIST[n][1])
这在第一种情况下给出了相同的TypeError,当列表的第三个条目是(f2,)时,IndexError: tuple index out of range。在
最后,星号符号也不起作用。这次它在调用f1时出错:for f,args in FUNCTION_LIST:
f(*args)
给出TypeError: f1() argument after * must be a sequence, not int。在
我已经没有东西可以试了。我仍然认为第一个应该有用。谁能给我指出正确的方向吗?在