I created the following class that represents a chest where toys (numbers) can be stored:
class Chest:
toys = []
def __init__(self):
return
def add(self, num):
self.toys.append(num)
return
The main code that uses this class is as follows:
room_of_chests = []
for i in range(3):
print "Chest", i
temp = Chest()
print "Number of toys in the chest:", len(temp.toys)
for j in range(5):
temp.add(j)
print "Number of toys in the chest:", len(temp.toys)
print ""
room_of_chests.append(temp)
So, for each iteration of i, I create a new Chest and make the variable temp point to it (correct?). So, in theory, in each iteration, temp would start with an empty chest and end with a chest with 5 toys (correct?).
Therefore, the output I am expecting is:
Chest 0
Number of toys in the chest: 0
Number of toys in the chest: 5
Chest 1
Number of toys in the chest: 0
Number of toys in the chest: 5
Chest 2
Number of toys in the chest: 0
Number of toys in the chest: 5
However, what I am actually getting is:
Chest 0
Number of toys in the chest: 0
Number of toys in the chest: 5
Chest 1
Number of toys in the chest: 5
Number of toys in the chest: 10
Chest 2
Number of toys in the chest: 10
Number of toys in the chest: 15
What am I doing wrong? Can someone give a quick explanation of how instantiation works in this case? And the rules of variables pointing to objects in Python? Thanks in advance.