The way that class variables in Python are handled does not make any sense to me. It seems that the scope of a class variable is dependent upon its type! Primitive types are treated like instance variables, and complex types are treated like class variables:
>>> class A(object):
... my_class_primitive = True
... my_class_object = ['foo']
...
>>> a = A()
>>> a.my_class_primitive, a.my_class_object
(True, ['foo'])
>>> b = A()
>>> b.my_class_primitive, b.my_class_object
(True, ['foo'])
>>> a.my_class_object.append('bar')
>>> b.my_class_primitive, b.my_class_object
(True, ['foo', 'bar'])
>>> a.my_class_primitive = False
>>> b.my_class_primitive, b.my_class_object
(True, ['foo', 'bar'])
>>> a.my_class_primitive, a.my_class_object
(False, ['foo', 'bar'])
Can someone please explain the following:
- Why does this feature exist? What is the logic behind it?
- If I want to use a primitive type (e.g. bool) as a class variable, how do I do it?