one.var = 2
actually adds the new instance variable var
by object but doesn't change the class variable var
and after adding the new instance variable var
, one.var
accesses the new instance variable var
as shown below. *If there are the same name class and instance variables, the same name instance variable is prioritized while the same name class variable is ignored when accessed by object:
class MyClass:
var = 1
one = MyClass()
two = MyClass()
print(one.var, two.var)
one.var = 2 # Adds the new instance variable by object
# ↓ Accesses the class variable by object
print(one.var, two.var)
# ↑
# Accesses the new instance variable by object
Output:
1 1
2 1
So, to change the class variable var
, you need to use the class name MyClass
as shown below:
class MyClass:
var = 1
one = MyClass()
two = MyClass()
print(one.var, two.var)
MyClass.var = 2 # Changes the class variable by the class name
print(one.var, two.var)
Output:
1 1
2 2
And basically, you should use class name to access class variables because you can always access class variables whether or not there are the same name instance variables. So, using class name is safer than using object to access class variables as shown below:
class MyClass:
var = 1
one = MyClass()
two = MyClass()
# Here # Here
print(MyClass.var, MyClass.var)
MyClass.var = 2 # Changes the class variable by the class name
# Here # Here
print(MyClass.var, MyClass.var)
Output:
1 1
2 2
My answer for How to access "static" class variables in Python? explains more about accessing class variables.