Why is this Python class copying another class contents?

Posted by fjfnaranjo on Stack Overflow See other posts from Stack Overflow or by fjfnaranjo
Published on 2010-04-21T15:24:31Z Indexed on 2010/04/21 15:33 UTC
Read the original article Hit count: 158

Hello guys.

I'm trying to understand an estrange behavior in Python.

I have the next 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 check the next question:

http://stackoverflow.com/questions/1876905/why-is-python-reusing-a-class-instance-inside-in-function

And a lot of Python reference, but I can not understand what is happening. I think is related with the newIntContainer identifier reutilization, but I do not understand it deeply.

Why Python appears to reused the last reference for the new object, even if I have added it to a permanent list? What can I do to resolve this behavior?

Thanks ;)

© Stack Overflow or respective owner

Related posts about python

Related posts about pass-by-value