See example below. Using the __class__ prefix with the class instance ‘object’ gives the expected result. Why is the class variable even available at the class instance ‘c()’ without the __class__ prefix? In what situation is it used?
>>> class c:
x=0
>>> c.x
0
>>> c().x
0
>>> c().__class__.x
0
>>> c.x += 1
>>> c.x
1
>>> c().x += 1
>>> c.x
1
>>> c().__class__.x += 1
>>> c.x
2
>>>
You can usefully think of it as instances “inheriting from” their class. IOW, when an attribute named
'atr'is looked up on the instancex(e.g. byx.atr), unless found in the instance itself it’s next looked up in the class (which in turn may cause lookup in the class’s bases, up themrochain).Most common single case:
You may not think of
fooas a “class variable”, but that’s because the term “variable” is really pretty meaningless in Python, which rather deals with names and attributes. There is no separate namespace for callable and non-callable objects at a given lexical scope: they all share the same namespace.So, for example, if you did
x.foo = 23then you couldn’t callx.foo()any more — because the lookup forx.foowould give you the value23, and that’s anint, not callable.Another way to look at this is that
present no deep difference — they’re all way to set class attribute
foo(one is not callable, two are; one is bound with adefstatement, two with assignments; there differences are not deep in terms of attribute lookup on instances of these classes).A typical use for non-callable attributes might be:
No need to give
zapan__init__withself.zep = Noneand a delegation to the superclass’s__init__(if any) — simpler to just inheritzop‘s__init__(if any) and use a class attribute as long as feasible (it will become an instance attribute instead if and only ifblubis called on that instance — also may save a tiny bit of memory for instances on whichblubis never called;-).