Want to keep learning?

This content is taken from the Raspberry Pi Foundation & National Centre for Computing Education's online course, Object-oriented Programming in Python: Create Your Own Adventure Game. Join the course to learn more.

Class variables vs instance variables

The attributes in a class are just variables used to store data within an object of that class. Each time we create an object, that object has its own set of these variables.

So far, all of the attributes we have created within the class have been instance variables. For example, our Enemy class has this attribute:


This attribute stores the weakness of the enemy represented by this instance of an enemy object. It can be set to a different value for each enemy object. Even if you were to set the same weakness for two different enemy objects, each object would have its own separate copy of the weakness. If you alter the weakness attribute of one object, the weakness attribute of another object of the same class is unaffected.

For our game this means that I can create two enemy objects, Dave and Brian, and set the weakness attribute to be different for each of them:


I like to imagine an instance variable like a notebook. My friend and I might each own the same notebook with the same cover, but these books are separate instances. If I draw in my notebook, the drawing does not also appear in my friend’s copy of it.

You may now be able to guess how a class variable is different from an instance variable. A class variable is like having a shared notebook, with its contents available to all notebook owners, i.e. all objects of that class.

You can create a class variable in Python by adding it outside of the constructor. Think back to week 1, when we created shape objects and drew them on the screen.

from shapes import Triangle, Rectangle, Oval
rect1 = Rectangle()

If you look at the shapes.py script from week 1, you will see this code inside the Shape class:

class Shape():
    paper = Paper()

paper is an example of a class variable – it is defined outside of the constructor, and self. is not part of its name. Data inside a class variable is shared by all objects of the respective class, so in this example, all objects of the class Shape (and of its subclasses) will be able to use the same paper object. We created the paper class variable in the shapes.py script so that, when you were using the script to draw shapes, all of them would appear in the same window rather than in separate windows.

Share this article:

This article is from the free online course:

Object-oriented Programming in Python: Create Your Own Adventure Game

Raspberry Pi Foundation