Class variables are shared between all instances of a class. That turns out to be pretty self-explanatory. Instance variables however are local to each instantiated object.
Here's an example, first we instantiate a bunch of classes.
In [19]: classes = [Class() for _ in range(5)]
In [20]: classes
Out[20]:
[<__main__.Class at 0x20bb290>,
<__main__.Class at 0x20bb2d0>,
<__main__.Class at 0x20bb310>,
<__main__.Class at 0x20bb350>,
<__main__.Class at 0x20bb4d0>]
And then we change the NUMBER
-variable of Class
In [21]: Class.NUMBER = "Hah!"
In [22]: print [x.NUMBER for x in classes]
['Hah!', 'Hah!', 'Hah!', 'Hah!', 'Hah!']
However, once you've instantiated the objects, you can change x.NUMBER
, and once you do the change is local to that object. I understand this can be quite confusing.
Where as we cannot even touch the foobar
-value yet, as it does not exist before the object is instantiated:
In [23]: Class.foobar
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-c680e41ebe07> in <module>()
----> 1 Class.foobar
AttributeError: type object 'Class' has no attribute 'foobar'
This has nothing to do with whether or not the class attributes are upper or lowercase. We can just as well access Class.foo
. The point is that everything before the __init__
exists before that class is instantiated to an object. Once that class is instantiated as an object, the object will have the instance attributes, namely obj.foobar
.