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 diagrams

To represent inheritance between classes, you can use a class diagram showing which classes inherit from which other classes. This may make the terms ‘superclass’ and ‘subclass’ easier to remember, as super- indicates the class above, while sub- indicates the class below. Some people like to compare these diagrams to family trees.

A class diagram. Character is at the top, with Enemy and Friend below it. Arrows point upward to Character from each of these.

In the diagram, each class is represented by a rectangle. An arrow points towards the class from which something is inherited.

Looking at a class diagram can also help us to understand polymorphism. If a class inherits from another class, it can also be considered to be an object of that class. For example, Enemy inherits from Character, so Enemy is a Character.

In week one, you used the gpiozero library to create an LED object in code to represent a physical LED.

An animation of an LED being connected to GPIO pin 17 of a Raspberry Pi

You can see in the diagram below that the class LED is a subclass of OutputDevice. This means that LED is an OutputDevice: it inherits the properties of a generic OutputDevice and adds some specialised methods of its own.

A class diagram with 3 levels of rectangles. The top level contains only "Device" Both "Input device" and "Output device" on the second level have arrows pointing upwards towards "Device". On the third level, "Button" and "Motion sensor" point upwards towards "Input device", and "LED" and "Buzzer" point upwards towards "Output device"

Buzzer is also a subclass of OutputDevice, but it has different functionality. If you look into the documentation, you will find that LED has a blink() method, whereas Buzzer has a beep() method. Both LED and Buzzer inherit the same on() and off() methods from OutputDevice.

Next steps

Now that you have character and enemy objects, it’s time to put them in rooms and allow your player to interact with them.

Share this article:

This article is from the free online course:

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

Raspberry Pi Foundation