Changing attribute in one class instance causes unexpected change in all instances

Hi, I think I don’t understand something fundamental about classes and objects. I’m trying to create two instances of a class and then change an attribute of one of those instances, but when I try a corresponding attribute in the other instance also changes:

#Testing object
class Test:
    name=''
    list=[]

    def __init__(self,name):
        self.name=name
    def change(self,num):
        self.list.append(num)

#Creating two instances of test
a=Test('qqqq')
b=Test('wwww')

#Changing list attribute of instance a
a.change('2')

#list attributes of both instances change
print(a.name)
print(a.list)             #expected [2] and I get [2]
print(b.name)
print(b.list)             #expected [] but I get [2]

The expected behaviour is:

  • print(a.list)==>“[2]”
  • print(a.list)==>“[ ]”
    but what I get is:
  • print(a.list)==>“[2]”
  • print(a.list)==>“[2]”

It’s a very basic example, so I can’t figure out what could be going wrong here.

Then you will need to add:

self.list = []

to the __ini__, so that only the instance list is affected.

So, if I understand correctly, when I’ve been referencing ‘list’ attribute, I was referencing a sort of generic attribute which belonged to the class itself and which was being inherited across all the instances of it and when I’ve edited it through a method in one of those objects I’ve changed the value which is inherited from class definition by all objects.

If I wanted to generate a ‘Test’ object with a unique attribute I should have mentioned it in the constructor.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.