Class and instance variables in Python

Vassilios Karakoidas
2 min readJul 1, 2024

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
foo

Now, 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'
>>>…

--

--

Vassilios Karakoidas

Software Engineer, Software Architect, Gamer and Researcher. Opinions are my own.