【发布时间】:2014-06-21 20:44:48
【问题描述】:
我有一个类的对象列表。当我更改在 append 函数中使用的对象时,列表也会更改。这是为什么?我来自 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 对象,所以它不应该在列表中。
【问题讨论】:
-
您不会将 副本 放入列表 - 它是对完全相同的对象的引用。
-
和提示有区别吗?因为在提示符下,当我更改变量时,列表不会更改。如何在列表中按值添加?
-
在提示中是一样的;没有看到确切的代码,我无法解释为什么你认为它不同。您不能“按值添加” - 它是 Python 中的所有引用。
current_state之类的名称和list之类的集合仅提供对底层对象的引用。如果您想要一个单独版本的对象,请定义一个复制它的方法 - 请参阅docs.python.org/2/library/copy.html -
在提示符下我做了以下操作:>>> b=[] >>> a=5 >>> b.append(a) >>> a=6 >>> b [5 ]