What is an object, and where have we seen objects before?

You have probably heard of object-oriented programming, but perhaps you are unsure about what it is. Maybe you have attempted to read guides or books but got lost in the jargon. Object-oriented programming is integral to many programming languages and it is simply a different style of programming. This course teaches you the key concepts in the familiar language of Python, providing a good foundation for moving to other languages such as Java, where the object-oriented style is preferred.

This course assumes that you already have some experience of using Python – you know how to create and run Python files and you have used the basics such as variables, selection, iteration, and functions. If you’ve used any libraries in your Python code, you’ve almost certainly already used objects without even realising it!

Let’s look at an example of an LED wired up to a Raspberry Pi computer. Don’t worry if you have never wired up an LED or done any other physical computing before – the most important thing here is the code!

 1.3 LED GP17

On the left of the diagram are the Raspberry Pi’s GPIO pins, which allow us to control components that are connected to them. The LED is connected to pin 17. To make the LED switch on, you would use the following Python code:

from gpiozero import LED
red = LED(17)			
red.on()

To interact with the LED, we have created an LED object which represents the physical LED in code. It has the name ‘red’ so that we can refer to that specific LED object.

red = LED(17)		

If we wired up another LED to pin 21, we could create another object with a different name to represent it:

green = LED(21)

What is an object?

Objects are used to model things in code. An object can represent a physical item, e.g. an LED; or a digital unit, e.g. a bank account or an enemy in a computer game. As such, an object is basically a group of data and functions. Because you can define your own objects, you can represent anything you like using an object!

Why would we want to make an object?

In our example, we created an LED object to model a physical LED in code. We also included a command to control the LED, in this case to turn it on. Such commands are called methods, i.e. custom functions specifically designed to interact with an object.

One of the benefits of using object-oriented programming is that unnecessary details can be abstracted away in the implementation of the methods. We do not need to know the specifics of exactly how a method works to be able to use it, we simply need to know that when we call the method, we will achieve a desired outcome. In our example, we don’t need to know anything about the on() method apart from the fact that using it on our LED object will make the physical LED light up.