繁体   English   中英

AttributeError:'NoneType'对象没有属性'append'

[英]AttributeError: 'NoneType' object has no attribute 'append'

我有一个奇怪的问题,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'对象没有属性'append'”,因为在foobar中top是None,尽管dir(top)打印了一个类型列表的完整属性和方法列表。 那么什么是错的? 我只是想将两个列表作为参数传递给这个递归函数。

您将top.append()结果传递给您的函数。 top.append()返回None:

>>> [].append(0) is None
True

你需要分别调用.append() ,然后传入top

top.append(listTop[i])
bottom.append(listBottom[i])
foobar(depth+1, top, bottom)

请注意, n=len(listTop)中的n=len(listTop)参数既冗余又只执行一次,即创建函数时。 每次调用该函数时都不会对其进行评估。 在任何情况下,您都可以从此处发布的版本中安全地省略它。

top.append(listTop[i])就地工作并返回None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM