Does a list in a Python class have the same object in two different instances?

I created a class:

class A: aList = [] 

I now have a function that instantiates this class and adds elements to the aList list.

Note: there are 2 items

 for item in items: a = A(); a.aList.append(item); 

I found that the first A and second object A have the same number of elements in their aList. I would expect the first object A to have the first element in its list, and the second object A to have the second element in its aList list.

Can someone explain how this happens?

PS:

I manage to solve this problem by moving aList inside the constructor:

 def __init__(self): self.aList = []; 

but I'm still interested in this behavior

+7
python
source share
4 answers

You have defined the list as a class attribute.

Class attributes are shared by all instances of your class. When you define the list in __init__ as self.aList , then the list is an attribute of your instance (self), and then everything works as you expected.

+9
source share

You mix class and object variables.

If you want objects:

 class A(object): def __init__(self): self.aList = [] 

in your example, aList is a class variable, you can compare it using the keyword "static" in other languages. The class variable, of course, is shared in all instances.

+3
source share

In Python, variables declared inside a class definition and not inside a method are class or static variables. You may be interested in looking at this answer to another question .

0
source share

This happened because list is a mutable object, and is created only once when the class is defined, so it becomes common when two instances are created. For example,

 class A: a = 0 #immutable b = [0] #mutable a = A() aa = 1 ab[0] = 1 b = A() print ba #print 0 print bb[0] #print 1, affected by object "a" 

Therefore, to solve the problem, we can use the constructor as what you mentioned. When we put a list in the constructor, whenever an object is created, a new list will also be created.

0
source share

All Articles