在Python的循环中,我将一个类的新实例分配给同一个变量,但是它一直指向旧实例?

Cra*_*ony 6 python class object instantiation

我创建了以下类,表示可以存储玩具(数字)的箱子:

class Chest:

  toys = []

  def __init__(self):
    return

  def add(self, num):
    self.toys.append(num)
    return
Run Code Online (Sandbox Code Playgroud)

使用此类的主要代码如下:

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)
Run Code Online (Sandbox Code Playgroud)

因此,对于i的每次迭代,我创建一个新的Chest并使变量temp指向它(正确吗?).所以,从理论上讲,在每次迭代中,temp都会以空胸开始,并以5个玩具的胸部结束(正确吗?).

因此,我期望的输出是:

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
Run Code Online (Sandbox Code Playgroud)

但是,我实际得到的是:

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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?在这种情况下,有人可以快速解释实例化的工作原理吗?而变量的规则指向Python中的对象?提前致谢.

mer*_*011 11

问题是你有一个class属性而不是一个实例变量.更改您的类,使其成为实例变量,方法是在__init__函数中创建它作为成员self.

此外,没有必要使用return在__init__.

class Chest:

  def __init__(self):
    self.toys = []


  def add(self, num):
    self.toys.append(num)
Run Code Online (Sandbox Code Playgroud)

如果你来自Java或C++这样的语言,这是一个常见的错误.