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.
The problem is that you have a class attribute and not an instance variable. Change your class to make it an instance variable by creating it in the __init__
function as a member of self
.
Also, there's no need to use return
in __init__
.
class Chest:
def __init__(self):
self.toys = []
def add(self, num):
self.toys.append(num)
This is a common mistake if you're coming from a language like Java or C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With