Why does this Python class copy the contents of another class?

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;)

+4
source share
2 answers

Since you made listOfInts a class variable that self.listOfInts refers self.listOfInts , whatever instance of self it might be; therefore, all append will go to the list of the same .

If this is not what you need, you need to make listOfInts an instance variable, for example, by setting self.listOfInts = [] at the beginning of the __init__ method.

+6
source

listOfInts is defined as a class variable.

Class variables are shared by all instances of the class.

This behavior is useful if you want to maintain the state associated with the class (a typical example would be when you want to know the number of instances of the created class.

If you want listOfInts to be unique for each instance, you must define it in init or another class method as self.listOfInts

+2
source

Source: https://habr.com/ru/post/1307561/


All Articles