我有一个类的对象列表。当我更改在追加函数中使用的对象时,列表也会更改。这是为什么?我来自 C++,所以这很奇怪。
我有以下代码:
class state:
def __init__(self):
self.x=list([])
self.possibleChests=list([])
self.visitedChests=list([])
def __str__(self):
print "x ",
print self.x
print "possibleChests ",
print self.possibleChests
print "visitedChests ",
print self.visitedChests
return ""
def addKey(self,key):
self.x.append(key)
def __eq__(self,other):
if isinstance(other,self.__class__):
return self.__dict__==other.__dict__
else:
return False
current_state=state()
current_state.addKey(4)
current_state.possibleChests.extend([1,2,4])
current_state.visitedChests.append(5)
visitedStates=list([])
visitedStates.append(current_state)
current_state.addKey(5)
if(current_state in visitedStates):
print "Got ya!!"
else:
print "Not in list!!"
我得到输出:
Got ya!!
我已经更改了 current_state 对象,因此它不应该出现在列表中。
Your state
对象是可变的。你打电话时current_state.addKey(5)
you modify current_state
但所有pointers到它仍然指向它。在 python 列表中只包含pointers到物体。对于可变的列表,您也有同样的事情:
l1 = [ 1, 2]
l2 = l1
l1.append(3)
l2
=> shows [1, 2, 3]
你不能对字符串有同样的东西(例如),因为它们是不可变的。你不能修改它们,只能指向另一个字符串
s1 = "abc"
s2 = s1
s1 = "def"
s2
=> shows "abc"
当您在循环外部创建对象并在循环中修改它并将其添加到列表中时,这是一个常见的错误来源:在循环结束时,您有一个列表,其中包含 n 次具有最后值的同一对象。这并不是 Python 所特有的,而是可以在 Java 中观察到,如果只存储指向可变对象的指针,甚至在 C 或 C++ 中也可以观察到。
C++ 示例(这不是好的 C++,但展示问题的最低限度)
class pair {
public:
int key;
int val;
}
pair* map[5];
pair p;
for (i=0; i<5; i++) {
p.key = i;
p.val = 2 * i;
map[i] = &p; // only store pointer
}
在循环结束时map
包含 5 个指向相同内容的指针pair
with key=4
and val=8
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)