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

Posted by zfranciscus on Stack Overflow See other posts from Stack Overflow or by zfranciscus
Published on 2010-05-03T09:25:45Z Indexed on 2010/05/03 9:38 UTC
Read the original article Hit count: 201

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about python

Related posts about beginner