【发布时间】:2016-04-22 08:54:48
【问题描述】:
我正在尝试在类的许多实例中使用特定对象。但是,每当我向该对象添加一个值时,事实证明它正在将该值添加到该类的所有其他实例的对象中。
This SO post 建议我的对象具有相同的 id,因为 GC 在同一内存上释放和加载对象。
节点类有一个对象邻居设置为neighbors = []
grid = [[node() for x in range(col)] for y in range(row)]
temp1 = grid[0][0].neighbors
temp2 = grid[4][0].neighbors
print id(temp1)
print id(temp2)
temp1.append("sth")
print temp1
print temp2
输出:
38412376
38412376
['sth']
['sth']
temp2 有一个空列表的可能解决方法是什么?
【问题讨论】:
-
你可能想看看
copy.deepcopy。 -
向我们展示
Node类__init__()方法的代码。您可能使用[]作为参数neighbors的默认值。这可能会导致您描述的行为。
标签: python memory memory-management garbage-collection nodes