[英]AttributeError: 'NoneType' object has no attribute 'append'
I have a weird problem with python passing a list as parameter to a function. 我有一个奇怪的问题,python将列表作为参数传递给函数。 Here is the code:
这是代码:
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)
It says "AttributeError: 'NoneType' object has no attribute 'append'", because top is None in foobar although dir(top) prints a full attribute and method list of a type list. 它说“AttributeError:'NoneType'对象没有属性'append'”,因为在foobar中top是None,尽管dir(top)打印了一个类型列表的完整属性和方法列表。 So whats wrong?
那么什么是错的? I just wanted to pass two lists as parameters to this recursive function.
我只是想将两个列表作为参数传递给这个递归函数。
You pass in the result of top.append()
to your function. 您将
top.append()
的结果传递给您的函数。 top.append()
returns None: top.append()
返回None:
>>> [].append(0) is None
True
You need to call .append()
separately, then pass in just top
: 你需要分别调用
.append()
,然后传入top
:
top.append(listTop[i])
bottom.append(listBottom[i])
foobar(depth+1, top, bottom)
Note that the n=len(listTop)
argument in the function is both redundant and only ever executed once, namely when you create the function. 请注意,
n=len(listTop)
中的n=len(listTop)
参数既冗余又只执行一次,即创建函数时。 It won't be evaluated each time you call the function. 每次调用该函数时都不会对其进行评估。 You can omit it safely from the version you posted here in any case.
在任何情况下,您都可以从此处发布的版本中安全地省略它。
top.append(listTop[i])
就地工作并返回None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.