python - 在 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 会不断在我的其他嵌套列表中添加值。
解决方案
您正在分配list_of_plants
给类,因此所有类实例将共享相同的列表。您应该将其分配为self
in 的属性__init__
(即,再缩进 4 个空格作为self.list_of_plants = []
),以便为每个单独的类实例创建一个新列表。
推荐阅读
- iis - 防止子域中 Windows Auth 上的重复用户名/密码质询
- php - 如何在laravel中为api后端返回JSON数据之前定义数据类型
- android - Seekbar thumb should be appear as in picture below in android
- uwp - 我无法在我的 Xbox UWP 应用弹出窗口中获得选择框
- java - 为什么当我使用包含时,我的 ArrayList 总是给出错误的数据?
- arrays - 用数组填充的循环仅填充第一个元素
- javascript - 通过 jQuery 追加 HTML 字符串
- javascript - 引导模式 (MVC) 中的 html.action
- dart - 在 Flutter 中如何影响父屏幕状态?
- c# - Resharper 建议添加参数