Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List in a Python class shares the same object over 2 different instances?

Tags:

python

I created a class:

class A:
    aList = []

now I have function that instantiate this class and add items into the aList.

note: there are 2 items

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

I find that the first A and the second A object has the same number of items in their aList. I would expect that the first A object will have the first item in its list and the second A object will have the second item in its aList.

Can anyone explain how this happens ?

PS:

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

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

but I am still curious about this behavior

like image 801
zfranciscus Avatar asked May 03 '10 09:05

zfranciscus


1 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.

like image 57
joaquin Avatar answered Sep 27 '22 18:09

joaquin