Creating a Song Class
00:00
With the introduction covered in the previous lesson, you can now move on to an example of how to implement descriptors. So you’ll be doing some coding. So please move to your favorite IDE and create a file called validator.py, all in lowercase.
00:20
In this file, you will be creating a Song class, and this class is not going to be a descriptor class. It is just going to be a standard class that we will build upon later in the course.
00:32
So create your Song class. Song is with a capital because it is the name of a class.
00:40
The idea is that we will instantiate this class, so create the __init__() method, which takes self as a first input parameter, and then we’ll have a title, which is a string, and also an artist, which is also a string.
00:58
All the __init__() method is going to do is to assign the values of title and artist to instance attributes, self.title and self.artist.
01:13
That’s it for the __init__() method. Then also create an instance method, which is the __str__() method. Now, you might know that the __str__() method allows you to apply the str() function to your class or to an instance of your class.
01:29
And when you do that, it will return well, whatever you want it to return. I would like you to type an f-string, and this f-string will just show the values really of title and artist.
01:41
So it will say, "This is {self.title Close the curly brackets, “by”, and an open curly brackets again, self.artist.
01:55
That’s it for the Song class. What’s left to do is to show you how that __str__() method works. So if you make sure you save this file and then open up your REPL in the directory where you have saved validator.py.
02:12
So in your REPL, from validator import Song with a capital S.
02:20
So that’s your Song class. Now create an instance of your Song class. I just call it s1 = Song( and the first input parameter was title.
02:30 So I’m going to use what I think is the best song of all time, and that’s “A Forest” by a band called The Cure.
02:40
So because you have implemented the __str__(), method in your Song class, you can now just apply the str() function to your s1, which is your class instance, and it will then return 'This is A Forest by The Cure'. So that is your Song class, and in the next lessons, you will build on this example.
Become a Member to join the conversation.
