如何避免具有相同ID的同一类的对象?

时间:2016-01-16 23:53:58

标签: python memory memory-management garbage-collection nodes

我正在尝试在类的许多实例中使用特定对象。但是每当我向该对象添加一个值时,结果是它将值添加到该类的所有其他实例的对象中。

This SO post建议我的对象具有相同的ID,因为GC释放并在同一内存中加载对象。

Node类的对象邻居设置为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有一个空列表可能的解决方法是什么?

1 个答案:

答案 0 :(得分:1)

我猜你在Node.__init__()中做了类似的事情:

class Node(object):
    def __init__(self, neighbors=[]):
        self.neighbors = neighbors

n1 = Node()
n2 = Node()

>>> n1.neighbors is n2.neighbors
True
>>> n1.neighbors.append('hi')
>>> n2.neighbors
['hi']

那是因为它们是同一个列表。你可以这样做:

class Node(object):
    def __init__(self, neighbors=None):
        if neighbors is not None:
            self.neighbors = neighbors
        else:
            self.neighbors = []

n1 = Node()
n2 = Node()

>>> n1.neighbors is n2.neighbors
False
>>> n1.neighbors.append('hi')
>>> n2.neighbors
[]

问题解决了吗?