python - 属性错误 : 'NoneType' object has no attribute 'append'

标签 python

我有一个奇怪的问题,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/

相关文章:

python - 如何将 jupyter notebook 目录中的模块导入到较低目录的 notebook 中?

python - z3变量类型切换

python - 在python中通过正则表达式提取多种日期格式

python - Django .latest() 值

python - 在 asdict 或序列化的数据类中包含属性的推荐方法是什么?

python - 如何在不更新光标的情况下读取文件?

python - 如何比较具有相同继承的@dataclass 的实例子类

python scrapy将多个页面的数据收集到一项(字典)中

python - 哪种字符串哈希算法生成 32 位或 64 位有符号整数?

python - Pygame 如何使用 LayeredUpdates() 更改图像层