What is an object?
Objects are used to model things in code. An object can represent a physical item, such as a display screen; or a digital unit, such as a bank account or an enemy in a computer game.
An object is a group of data and functions. Such functions are called methods; they are custom functions specifically designed to interact with an object. And because you can define your own objects, you can represent anything you like using an object.
Where may you have seen objects before?
In Python, everything is an object. String and integer variables, lists, and even functions are individual objects. While you may not have created your own objects, or been aware of them, you will have used objects in your Python programs.
This code would create a list of numbers:
numbers = [1, 2, 3]
numbers is a list object that contains data and methods.
It contains the data
1, 2, 3 and methods which allow you to manipulate this data.
You could use the
append method to add a new item to the end of the list, e.g.
The data within the
numbers object would be modified to contain the new number, i.e.
1, 2, 3, 4.
You can view all the list object methods in the Python documentation.
I’d like you to think about 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 important thing here is the code.
On the left of the diagram is Raspberry Pi’s GPIO pins. GPIO pins allow you 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, an
LED object is created that represents the physical LED in code. The object is given the name
red so that you can refer to that specific LED object.
red = LED(17)
If another LED were wired up to pin 21, you could create another object with a different name to represent it:
green = LED(21)
Why would you want to make an object?
In the example above, the code also used a method to control the LED, in this case to turn it on.
One of the benefits of using object-oriented programming is that unnecessary details can be abstracted away in the implementation of the methods. You do not need to know the specifics of exactly how a method works to be able to use it; you simply need to know that when you call the method, the desired outcome will be achieved.
You don’t need to know anything about the
on() method, apart from the fact that using it on the LED object will make the physical LED light up. Similarly you didn’t need to know how the
append() method worked when you added an item to the end of the
What methods have you used in Python before? You may have used a method that looked like
object.method(). Share any methods and their objects that you’ve come across before in the comments section.