Loading video player…

Discussing the Song Class

00:00 In the previous lesson, you have created the Song class. And in this lesson, I would like to spend a minute to talk through the code and see how you can improve it, and of course, how you can incorporate descriptors.

00:14 If you focus your attention to line 4 the __init__ method. You have asked title and artist to be strings, but actually there is nothing in the code that would stop you to have integers or anything that is not a string feeding into title and artist.

00:31 Now we would want that to be a string. So therefore the idea is to build in validation to make sure that title and artist are indeed strings.

00:39 Now, there are two options I can think of. One, you could build in a validation instance method, for example, in the Song class. But I’m not loving that solution because validating a string isn’t unique to a Song.

00:53 It could be needed for names of books, for example, because we’re validating strings, not songs. So I’m not liking that very much. I mean, the second option is that you could separate out the validation of the input parameters into another class that’s called StringValidation class, for example.

01:14 And the advantage is that that class can then be reused by other classes than Song. And it can be coded actually by other people. It could be maintained by others, so that to me feels like a much neater solution.

01:30 Now I want this validation to apply to the title, okay? And later also to the artist. But let’s just do it for the title first.

01:39 And also I want that to happen, that validation, as soon as a user enters the title. So what I want to happen is as soon as a user enters a song where the title isn’t a string, I would like a message to come up and say, Hey, this needs to be a string.

01:55 So in other words, I want that to happen as soon as the user creates a Song instance.

02:02 Now, when the user creates a Song instance, then that is when the __init__ method is being triggered. So I would like to build that into the __init__ method.

02:12 And ideally, I would like to do this without adding any code. And this is exactly what you can do with the descriptor because the magic of a descriptor is that you decide what happens when the dot notation is being used.

02:26 So on line five, title is being accessed using the dot notation. So that is when I would like that validation to happen, and that is what your descriptor will allow you to do. In the next lesson then, you will build the descriptor.

Become a Member to join the conversation.