- Explain what a Python class is and why it is useful
- Create a simple class with attributes
- Use the
__init__method to set up a class correctly - Create several Track objects and display them in the song list
So far you have used Python's built-in types to store data: strings, numbers, lists. But what if you want to store several related pieces of data together? A class lets you bundle data under a single name.
Think of a class like a template or blueprint: once you have defined the blueprint you can make as many individual copies (called objects or instances) as you like.
Part 1 β A song has several pieces of information
Every song in your MP3 player has a title, an artist, a file on the SD card, and (optionally) a set of lyrics. Without a class you would need a separate variable for every piece of data for every song β that gets messy very quickly!
Instead, we can define a Track class once and then use it to create a
neat bundle for each song:
# A blueprint that describes what every Track looks like
class Track:
artist = ""
title = ""
# Create two Track objects from the blueprint
song1 = Track()
song1.artist = "Oasis"
song1.title = "Wonderwall"
song2 = Track()
song2.artist = "Rick Astley"
song2.title = "Never Gonna Give You Up"
print(song1.title) # Wonderwall
print(song2.artist) # Rick Astley
Each object has its own copy of title and artist. You access
them with a dot: song1.title.
Part 2 β The shared-variable trap πͺ€
The code above looks fine, but it contains a hidden bug. Try this in the Python shell or as a quick experiment:
class Track:
artist = ""
song1 = Track()
song2 = Track()
song1.artist = "Oasis"
print(song1.artist) # Oasis β fine
print(song2.artist) # "" β still fine here, butβ¦
# Now change artist on the CLASS itself:
Track.artist = "Coldplay"
print(song1.artist) # Oasis β song1 has its own copy
print(song2.artist) # Coldplay β song2 had NO copy yet, so it uses the class's
When you write artist = "" inside the class but outside any method,
it belongs to the class itself, not to each individual object.
Any object that has never been given its own value will just borrow the class's value β
and if the class's value changes, so does theirs.
Part 3 β Fix it with __init__
The solution is to give every object its own values right when it is created.
Python provides a special method for exactly this: __init__
(short for initialise). It runs automatically every time you create a new object.
class Track:
def __init__(self, title, artist):
self.title = title
self.artist = artist
self?
self refers to this particular object. When you write
self.title = title you are saying "store the value of title
inside this Track object". Every object gets its very own copy.
Now creating tracks is much neater, and each one is completely independent:
song1 = Track("Wonderwall", "Oasis")
song2 = Track("Never Gonna Give You Up", "Rick Astley")
song3 = Track("Bohemian Rhapsody", "Queen")
print(song1.title) # Wonderwall
print(song2.artist) # Rick Astley
Part 4 β Adding tracks to the player
The pypod module gives you a function called add_track().
Pass it a Track object and it will appear in the song selection list on screen.
Here is the full main.py you will write in this lesson:
from pypod import Track, add_track, start
# Define the Track class
class Track:
def __init__(self, title, artist):
self.title = title
self.artist = artist
# Create some tracks and add them to the player
song1 = Track("Wonderwall", "Oasis")
song2 = Track("Never Gonna Give You Up", "Rick Astley")
song3 = Track("Bohemian Rhapsody", "Queen")
add_track(song1)
add_track(song2)
add_track(song3)
# Start the app β always the last line
start()
You may have noticed the import at the top includes Track from
pypod. The teacher has already written a full version of the class for
you there. You are re-writing it yourself in this lesson to understand how it works;
in later lessons you will use the pypod version directly.
- Type out the class definition and make sure you get the indentation right.
- Create three
Trackobjects β use song titles you actually like! - Call
add_track()for each one and run the code. - Check that all three songs appear in the list on the device screen.
- Add a
yearattribute to yourTrackclass (inside__init__). - Create five tracks, all from different years.
- Can you write a
printstatement that shows "Wonderwall was released in 1995" (using your object's attributes)?