fjf*_*njo 4 python variables class
我试图理解Python中的异化行为.
我有下一个python代码:
class IntContainer:
listOfInts = []
def __init__(self, initListOfInts):
for i in initListOfInts:
self.listOfInts.append(i)
def printInts(self):
print self.listOfInts
if __name__ == "__main__":
intsGroup1 = [1,2,3,4]
intsGroup2 = [4,5,6,7]
intsGroups = [intsGroup1,intsGroup2]
intsContainers = []
for ig in intsGroups:
newIntContainer = IntContainer(ig)
intsContainers.append(newIntContainer)
for ic in intsContainers:
print ic.listOfInts
Run Code Online (Sandbox Code Playgroud)
我希望得到类似的东西:
[1, 2, 3, 4]
[4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)
但我得到:
[1, 2, 3, 4, 4, 5, 6, 7]
[1, 2, 3, 4, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)
我检查了下一个问题:
还有很多Python参考,但我无法理解发生了什么.我认为与newIntContainer
标识符重用度有关,但我不深刻理解.
为什么Python似乎重用了新对象的最后一个引用,即使我已将它添加到永久列表中?我该怎么做才能解决这个问题?
谢谢 ;)
既然你创建listOfInts
了一个类变量,那self.listOfInts
就是访问self
它,它可能是什么实例; 所以,所有的append
s都会进入同一个列表.
如果那不是你想要的,你需要创建listOfInts
一个实例变量,例如通过self.listOfInts = []
在__init__
方法的开头指定.
归档时间: |
|
查看次数: |
170 次 |
最近记录: |