Question
If a class contains a class variable and that class variable is changed in one instance, do all the other instances of the class see the change?
Answer
Yes, a class variable is shared by all objects of a class. If it is changed via one object, all of the other objects will see the changed value. The following code example shows a class variable updated by the reference to object1
.
class TestClass:
name = "Joe"
def __init__(self, id):
self.id = id
object1 = TestClass(1)
object2 = TestClass(2)
print(object1.id,object1.name)
# (1, 'Joe')
print(object2.id,object1.name)
# (2, 'Joe')
object1.name = "New Name"
print(object1.id,object1.name)
# (1, 'New Name')
print(object2.id,object1.name)
# (2, 'New Name')