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?
本问题已经有最佳答案,请猛点这里访问。
我创建了以下类,表示可以存储玩具(数字)的箱子:
1 2 3 4 5 6 7 8 9 10 | class Chest: toys = [] def __init__(self): return def add(self, num): self.toys.append(num) return |
使用此类的主要代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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) |
所以,对于我的每次迭代,我都创建一个新的胸腔,并使变量temp指向它(对吗?)因此,理论上,在每次迭代中,temp将从一个空箱子开始,以一个有5个玩具的箱子结束(对吗?).
因此,我期望的输出是:
1 2 3 4 5 6 7 8 9 10 11 | 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 |
然而,我真正得到的是:
1 2 3 4 5 6 7 8 9 10 11 | 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 |
我做错什么了?在这种情况下,有人能快速解释实例化是如何工作的吗?在python中指向对象的变量规则是什么?事先谢谢。
问题是您有一个类属性而不是实例变量。通过在
另外,在
1 2 3 4 5 6 7 8 | class Chest: def __init__(self): self.toys = [] def add(self, num): self.toys.append(num) |
如果你来自像Java或C++这样的语言,这是一个常见的错误。