Creating a Descriptor Class
00:00
In this lesson, you will be creating a descriptor class that will be used to validate that title is a string. You know that the magic of the descriptor classes happens when the dot notation is being used. The dot notation is being used for title anyway in two places as far as I can see in the Song class that’s firstly on line five.
00:23
It says self.title = title. So this is where self.title is being updated, a value is being assigned to it, and then on line nine, self.title is being used but is not updated.
00:40
So that links to two different dunder methods in your descriptor class. With that in mind, go to the top of your file and create your StringValidator class.
00:56
So StringValidator is using camel case as is the convention for class names. The first dunder method to implement is the __get__() method, so the __get__, open brackets,
01:13
and then self, obj, and objtype=None.
01:24
And for now, just pass. So __get__() is the dunder method that is associated with retrieving the value. So when the dot notation is being used, now that is line 12, the dot notation is being used for title without the value of title being updated.
01:44
Then the __get__() dunder method will be triggered. When the value is being updated, as is the case in line eight, then that will trigger the __set__() dunder method.
01:57
So, and then again, self, obj, and value.
02:07
But now again, pass. The final step in setting up your basic structure is to link the Song class to the StringValidator class.
02:20
And that needs to happen in a particular way. The Song class needs to have a class attribute. Now, it’s important that it is a class attribute.
02:29 This will have no effect for instance attributes. And so this class attribute needs to have the name of the attribute for which you want to trigger the magic.
02:40
So that needs to be title. And to this class attribute, you need to assign an instance of the descriptor class, so in your case that is StringValidator.
02:55 And then don’t forget the parentheses to make it an instance.
03:00 And that’s the basic setup of your descriptor class. Before you do more coding though, let me talk you through the input parameters of the description methods in the next lesson.
Become a Member to join the conversation.
