【发布时间】:2012-08-06 16:08:55
【问题描述】:
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)。前两个函数调用正常工作 - 元组的 content 被传递,而不是元组本身。
去掉有问题的列表条目中的空参数元组并不能解决问题:
FUNCTION_LIST[2] = (f2,)
for f,arg in FUNCTION_LIST:
f(arg)
结果为@987654324@。
我也尝试过迭代索引而不是列表元素。
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。
我已经没有东西可以尝试了。我仍然认为第一个应该工作。谁能指出我正确的方向?
【问题讨论】:
标签: python list function arguments tuples