I saw the following Python documentation which says that “define variables in a Class” will be class variables:
“Programmer’s note: Variables defined in the class definition are
class variables; they are shared by all instances. “
but as I wrote sample code like this:
class CustomizedMethods(object):
class_var1 = 'foo'
class_var2 = 'bar'
cm1 = CustomizedMethods()
cm2 = CustomizedMethods()
print cm1.class_var1, cm1.class_var2 #'foo bar'
print cm2.class_var1, cm2.class_var2 #'foo bar'
cm2.class_var1, cm2.class_var2 = 'bar','for'
print cm1.class_var1, cm1.class_var2 #'foo bar' #here not changed as my expectation
print cm2.class_var1, cm2.class_var2 #'bar foo' #here has changed but they seemed to become instance variables.
I’m confused since what I tried is different from Python’s official documentation.
When you assign an attribute on the instance, it is assigned on the instance, even if it previously existed on the class. At first,
class_var1andclass_var2are indeed class attributes. But when you docm1.class_var1 = "bar", you are not changing this class attribute. Rather, you are creating a new attribute, also calledclass_var1, but this one is an instance attribute on the instancecm1.Here is another example showing the difference, although it still may be a bit tough to grasp:
At first,
a.var is A.varis true (i.e., they are the same object): sinceadoesn’t have it’s own attribute calledvar, trying to access that goes through to the class. After you giveaits own instance attribute, it is no longer the same as the one on the class.