Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
dictionary shared between objects for no reason?
class Player():
zones = {}
def __init__(self):
self.zones['hand'] = []
def InitHand(self):
for a in range(5):
self.zones['hand'].append(a)
lst = []
lst.append(Player())
lst.append(Player())
lst[0].InitHand()
print lst[1].zones['hand']
This prints "[0, 1, 2, 3, 4]", but I only initialized the 0th element... Changing them to arrays as below fixes the problem, but for the life of me I can't figure out why this happens.
class Player2():
zones = []
def __init__(self):
self.zones = []
def InitHand(self):
for a in range(5):
self.zones.append(a)
lst = []
lst.append(Player2())
lst.append(Player2())
lst[0].InitHand()
print lst[1].zones
This prints "[]" as expected