I have a list of objects of a class. When I change the object that I use in the append function, the list also changes. Why is that? I am coming from C++ so this is quite strange.
I have the following code:
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!!"
And I get the output:
Got ya!!
I have changed the current_state object so it should not be in the list.