A blog about SQL, technology, and careers in technology.

Main menu

Post navigation

Class and instance variables in Python 2.7

The differences and interactions between class variables and instance variables are well described in the Python 2.x documentation, but they can be slightly subtle in some cases and I recently spent quite some time troubleshooting an issue even though I should have known better.

To put it simply, class variables are defined outside of any method of the class, normally right below the doc string. Class variables can be referenced directly from the class, and this can be used as one way to make an enumerated constant, or they can be referenced from any instance in the class. Instance variables are defined inside a method, normally __new__ or __init__, and they are local to that instance.

Class variables can be useful for constants that will need to be used by all instances of the class, or that are meant to be accessed directly from the class. They can also be used to set defaults for instance variables. But there it is important to remember that if the value of a class variable is changed, then all instances that call to the class variable will reflect that change. So, to carry on with our contrived TestClass:

TestClass.c = 1
assert testInst.c == 1 #Referring back to the class, so it changed too.

But when an instance has an attribute of the same name as an instance that essentially hides the class attribute. And assigning a value to an attribute of an instance will assign it just to that instance attribute, even if it needs to create it to do it. So: