Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a loop in Python, I assign a new instance of a class to the same variable, but it keeps pointing to the old instance? [duplicate]

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.

like image 312
CrazyJony Avatar asked May 20 '15 22:05

CrazyJony


1 Answers

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++.

like image 127
merlin2011 Avatar answered Oct 07 '22 01:10

merlin2011