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.

Cement your knowledge of objects

Note: There is no speech on the video above, and all of the steps in the video are described below.

So far, you have learnt that an object has attributes (or pieces of data) stored inside it, and methods we can call on it to give it instructions.

As I mentioned briefly earlier, a class is like a blueprint for creating objects. I like to think of a class as being similar to a cookie cutter: it is a template for all the cookie objects you make.

an illustration of a cookie cutter over some dough

You can make as many instances of cookie objects as you want, and they will all start off from the same template.

an illustration of cookies being cut using a cookie cutter

an illustration of cookie shapes that are all the same

If you like, you can customise each instance of a cookie object, perhaps by adding some icing or some sprinkles. But whenever you make cookies, you use the same cookie cutter template.

an illustration of cookies all with different designs

Imagine you have created a Cookie class in a module called baking which accepts a list of toppings.

You could create some cookies using the following code.

from baking import Cookie

sprinkled = Cookie(["sprinkles"])
iced_chocolate = Cookie(["icing", "chocolate chips"])

Think back to the turtle race program that you wrote. You created four instances of turtle objects from the Turtle class and customised the attributes of each turtle object by changing its colour and position. You used the forward method to move each turtle object, which drew a line across the screen based on that turtle’s colour attribute.

Next steps

Over the next few steps you’ll use some different objects and combine them into a single program.

Share this video:

This video is from the free online course:

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

Raspberry Pi Foundation