tags:

views:

292

answers:

3

What I want is this behavior:

class a:
    list=[]

y=a()
x=a()


x.list.append(1)
y.list.append(2)
x.list.append(3)
y.list.append(4)

print x.list
    [1,3]
print y.list
    [2,4]

of course, what really happens when I print is:

print x.list
    [1,2,3,4]
print y.list
    [1,2,3,4]

clearly they are sharing the data in class a. how do I get separate instances to achieve the behavior I desire?

+4  A: 

You declared "list" as a "class level property" and not "instance level property". In order to have properties scoped at the instance level, you need to initialize them through referencing with the "self" parameter in the __init__ method (or elsewhere depending on the situation).

You don't strictly have to initialize the instance properties in the __init__ method but it makes for easier understanding.

jldupont
+14  A: 

You want this:

class a:
    def __init__(self):
        self.list = []

Declaring the variables inside the class declaration makes them "class" members and not instance members. Declaring them inside the __init__ method makes sure that a new instance of the members is created alongside every new instance of the object, which is the behavior you're looking for.

abyx
thanks, exactly what I was looking for.
8steve8
An added clarification: if you were to reassign the list property in one of the instances, it would not affect the others. So if you did something like `x.list = []`, you could then change it and not affect any others. The problem you face is that `x.list` and `y.list` are the same list, so when you call append on one, it affects the other.
Matt Moriarity
+3  A: 

Yes you must declare in the "constructor" if you want that the list becomes an object property and not a class property.

ocell