Why do you see what you see? You have created an instance of TestVarClass
and assigned it to testVar
class attribute, which is accessible from that class and each of its instances (but is still the same class attribute and refers to the same object). It would be the same as a simplified example of:
>>> class C:
... pass
...
>>> C.a = C()
>>> C.a
<__main__.C instance at 0x7f14d6b936c8>
>>> C.a.a
<__main__.C instance at 0x7f14d6b936c8>
class C
now having attribute a
itself being instance of C
. I can access C.a
and since that is instance of C
and I can access its C.a
(or C.a.a
). And so on. It's still the very same object though.
Python doesn't really have static variables. Well, it sort of does, but as a side effect of default argument values being assigned once when a function is being defined. Combine that with behavior (and in-place modification) of mutable objects. And you essentially get the same behavior you'd expect form a static variable in other languages. Take the following example:
>>> def f(a=[]):
... a.append('x')
... return id(a), a
...
>>> f()
(139727478487952, ['x'])
>>> f()
(139727478487952, ['x', 'x'])
>>>
I am not entirely sure what exactly are you after. Once assigned, class attribute lives with the class and hence could be considered static in that respect. So I presume assign only once behavior interests you? Or to expose the class attribute in instances without being able to assign to it instances themselves? Such as:
>>> class C:
... _a = None
... @property
... def a(self):
... return self._a
...
>>> C._a = C()
>>> c = C()
>>> print(c.a)
<__main__.C object at 0x7f454bccda10>
>>> c.a = 'new'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
Or if you wanted to still use a
in both class and instance?
>>> class C:
... a = None
... def __setattr__(self, name, value):
... if name == 'a':
... raise TypeError("Instance cannot assign to 'a'")
... super().__setattr__(name, value)
...
>>> C.a = C()
>>> c = C()
>>> c.a
<__main__.C object at 0x7f454bccdc10>
>>> C.a
<__main__.C object at 0x7f454bccdc10>
>>> c.a = 'new_val'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __setattr__
TypeError: Instance cannot assign to 'a'
Essentially read-only variable (static or not) already sounds a bit like a contradictio in adiecto (not really as much of a variable), but (long story short) I guess the question really is, what is it that you're trying to do (problem you're trying to solve) in a context... and perhaps based on that we could try to come up with a reasonable way to express the idea in Python, but as given without further qualification, Python does not have anything it'd call static read-only variables.