tags:

views:

58

answers:

3

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

+1  A: 

You are confusing 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 with using the 'static' keyword in other languages. The class variable of course is shared over all instances.

KillianDS
Thanks for pointing this out. I come from Java background where we have a 'static' keyword for static variables. Now I understand the reasoning behind this. Cheers =)
zfranciscus
+4  A: 

You have defined the list as a class atribute.

Class atributes are shared by all instances of your class. when you define the list in init as self.aList, then the list is an atribute of your instance (self) and then everything works as you expected.

joaquin
A: 

In Python, variables declared inside the class definition, instead of inside a method, are class or static variables. You may be interested in taking a look at this answer to another question.

plok