我有一个奇怪的问题,python 将列表作为参数传递给函数。这是代码:
def foobar(depth, top, bottom, n=len(listTop)):
print dir(top)
print top.append("hi")
if depth > 0:
exit()
foobar(depth+1, top.append(listTop[i]), bottom.append(listBottom[i]))
top = bottom = []
foobar(0, top, bottom)
它说“AttributeError: 'NoneType' object has no attribute 'append'”,因为 foobar 中的 top 是 None 尽管 dir(top) 打印类型列表的完整属性和方法列表。 那怎么了?我只是想将两个列表作为参数传递给这个递归函数。
最佳答案
您将top.append()
的结果 传递给您的函数。 top.append()
返回无:
>>> [].append(0) is None
True
需要单独调用.append()
,然后传入top
:
top.append(listTop[i])
bottom.append(listBottom[i])
foobar(depth+1, top, bottom)
请注意,函数中的 n=len(listTop)
参数是多余的,并且只执行一次,即当您创建函数时。不会在您每次调用该函数时对其进行评估。在任何情况下,您都可以从此处发布的版本中安全地省略它。
关于python - 属性错误 : 'NoneType' object has no attribute 'append' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13555551/