Write a program using an object
Start to create your object-oriented text-based adventure game
Extend other people’s classes
Create an enemy in the room
Recap Week 3
Extending your knowledge of OOP
Finish your game
End of the course
To start, 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 object is created of the class LED that represents the physical LED in code. The object has the name red so that we 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)
Objects are used to model things in code. An object can represent a physical item, such as an LED; 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. And because you can define your own objects, you can represent anything you like using an object.
In the example, an LED object was created to model a physical LED in code.
The code also included a command to control the LED, in this case to turn it on.
red.on()
Such commands are called methods; they are 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. 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.
If you’ve programmed with Python before, have you used any objects? You may have used a method that looked like object.method(). Share any objects that you’ve come across before in the comments section.