I am trying to understand pop behavior in Python.
I have the following python code:
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
I expect to get something like:
[1, 2, 3, 4] [4, 5, 6, 7]
But I get:
[1, 2, 3, 4, 4, 5, 6, 7] [1, 2, 3, 4, 4, 5, 6, 7]
I have the following question:
Why python reuses an instance of a class inside a function
And a lot of links to Python, but I can not understand what is happening. I think this is due to the reuse of the newIntContainer identifier, but I do not understand it deeply.
Why is Python reusing the last link for a new object, even if I added it to the permalink? What can I do to allow this behavior?
Thanks;)