31Dec Interesting Python Static Attributes
So I was playing around with some code in Python today and was curious about static members of a class (I guess that is what you would call it). I wanted to know if I set an attribute at the class level and change it, would all the instances see that change or if each instance is separate.
Here is some code I played with:
>>> class T:
... build_location = None
... def get_location(self):
... return self.build_location
...
>>> t = T()
>>> print t.get_location()
None
>>> T.build_location = "hello"
>>> print t.get_location()
hello
>>> t.build_location = "there"
>>> print t.get_location()
there
>>> print T.build_location
hello
>>> T.build_location = "hello"
>>> print t.get_location()
there
>>>
So, what I did was set an attribute on the class level that everyone can see without an instance of the class. When I create an instance it can see that attribute just like I can from just doing T.build_location. When I change the static variable then the instance sees that change as well (which is what I was hoping for).
Now, the interesting part is that if I use an instance of the class to change the variable, that variable becomes local to that instance as you can see above when I printed the class’s T.build_location. Now I tried to set the class level attribute back to “hello” and that works but now it does not change what the instance sees!
This is not any earth shattering news but I thought it was interesting when I saw it.

