首页 > 解决方案 > 在 Python 类的嵌套列表中追加元素

问题描述

这是我的代码:

class Plant:
    def __init__(self,name):
        self.name = name

class Garden:
    def __init__(self,name):
        self.name = name

    list_of_plants = []

list_of_gardens = []
list_of_gardens.append(Garden("garden1"))
list_of_gardens.append(Garden("garden2"))

list_of_gardens[0].list_of_plants.append(Plant("Basil"))

print("Plant1: ", list_of_gardens[0].list_of_plants[0].name)
print("Plant2: ", list_of_gardens[1].list_of_plants[0].name)

输出:

Plant1: Basil
Plant2: Basil

为什么 Basil 会出现在两个嵌套列表中?我什至没有影响第二个列表中的值!即使当我查看指针时,一切看起来都不错,但 append 会不断在我的其他嵌套列表中添加值。

标签: pythonlistpointersnestedappend

解决方案


您正在分配list_of_plants给类,因此所有类实例将共享相同的列表。您应该将其分配为selfin 的属性__init__(即,再缩进 4 个空格作为self.list_of_plants = []),以便为每个单独的类实例创建一个新列表。


推荐阅读