2

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]
0

1 Answer 1

3

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())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.