Vishnu Vardhan
Vishnu Vardhan

Reputation: 57

Problem in understanding Python memory allocation for list of objects

I want to store different values in different object's attributes. But in the following program, a change made in one object's class variable affects others also. It seems all objects refer to a same class variable(memory location)? (it shouldn't be) but the output tells that...

class abc:
    list1=[]
    list2=[1,2,3,4,5,6,7,8,9,10]
    def disp_obj(self):
        print("List1=",self.list1,"List2=",self.list2)
    def change(self):
        self.list1.append(self.list2.pop())
xyz=[]
for i in [1,2,3,4]:
    xyz.append(abc())
for i in [0,1,2,3]:
    xyz[i].change()
    xyz[i].disp_obj()

Output:

List1= [10] List2= [1, 2, 3, 4, 5, 6, 7, 8, 9]
List1= [10, 9] List2= [1, 2, 3, 4, 5, 6, 7, 8]
List1= [10, 9, 8] List2= [1, 2, 3, 4, 5, 6, 7]
List1= [10, 9, 8, 7] List2= [1, 2, 3, 4, 5, 6]

But my expected output is:

List1= [10] List2= [1, 2, 3, 4, 5, 6, 7, 8, 9]
List1= [10] List2= [1, 2, 3, 4, 5, 6, 7, 8, 9]
List1= [10] List2= [1, 2, 3, 4, 5, 6, 7, 8, 9]
List1= [10] List2= [1, 2, 3, 4, 5, 6, 7, 8, 9]

Upvotes: 2

Views: 35

Answers (1)

Barmar
Barmar

Reputation: 780851

All your abc() instances are sharing the same list1 and list2 attributes, since they're declared in the class declaration.

You should create new ones in the __init__ method.

class abc:
    def __init__(self):
        self.list1=[]
        self.list2=[1,2,3,4,5,6,7,8,9,10]
    def disp_obj(self):
        print("List1=",self.list1,"List2=",self.list2)
    def change(self):
        self.list1.append(self.list2.pop())

Upvotes: 3

Related Questions