class A(object): inst = 1
inst is the class variable
Yes. but no.
Usually, in object oriented languages like c++, java, the class variables are shared across instances. But here something different.
class variables are shared across instances in some sense.
In : class A(object): ...: inst = 1 ...: In : In : a = A() In : b = A() In : a.inst Out: 1 In : b.inst Out: 1 In : A Out: __main__.A In : A.inst = 22 In : a.inst Out: 22 In : b.inst Out: 22
in the above sample, the change
A.inst = 22 reflect across all instances
In : class A(object): ...: inst = 1 ...: In : a = A() In : b = A() In : a.inst = 3 # Notice here this is the culprit In : b.inst Out: 1 In : A.inst = 5 # Change in class variable In : b.inst Out: 5 In : a.inst Out: 3 # Why this did not get update?
line no: 82 is the important change. Our usual understanding is, the class variable can be accessed via instance or class name. So, we can change the class varialbe via instance also. This will update entirely. It is absolutely wrong. Since, when you change the class variable’s value by instance, the scope gets changed.
a.inst = 3 means, one instance specific attribute is created dynamically which is reserved for this particular instance. So,
a.inst is not exactly looking for class variable if instance attribute existing.
just try it like below
you should be getting latest class variable value which is
5 in our case.
This lack of understanding may cost one opportunity. Lets be aware.