Class and instance variables in Python
July 1, 2024 · Programming

Yesterday i had a talk with my friend Dimitris. He told me about a problem that he had with Python. I was shocked when i realised that Python has a “mixed” way to declare class and instance variables (not sure about the terminology though).
When you declare a class in Python, and write a variable inside the class body, then automatically it is class variable (like the static keyword in Java). For example:
>>> class k:
... i = "foo"
...
>>> print k.i
fooNow, if you declare a method foo() that return this attribute you should write:
>>> class k:
... i = "foo"
... def get(self):
... return k.i
...
>>> k().get()
'foo'We can see that to run the method you need an instance of k, even if you refer to a statically-accessed member.
The problem gets even worse if you want to create an instance variable, which is a variable that exists ONLY for this instance (keep that in mind all Java people :) ). We could do that with something like:
>>> class k:
... i = 'foo'
... def get_static_i(self):
... return k.i
... def get_instance_i(self):
... return self.i
... def __init__(self):
... self.i = 'not foo'
...
>>> k.i
'foo'
>>> k().get_static_i()
'foo'
>>> k().get_instance_i()
'not foo'This looks paranoid right? … Well it is a little, if you have not understood the basic python concepts. Everytime you declare a self.[variable] in a class, then always you declare an instance variable, when you do it on a class body, always a Class variable. It is funny right? and look ambiguous but it is not.
The only thing that i haven’t understood yet, is how you make a Class variable read-only :). Actually, you cannot :). Lets just agree that classes, are glorified structs.