Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Adjusting Attribute Names

00:00 In this lesson, you’re going to make your code more dynamic by avoiding hard-coded attribute names. So in lines 7 and 8, and in lines 13 and 14, you are using .title, which works if you are validating your title.

00:16 But if you’re validating the artist, of course this wouldn’t work anymore. Now there is a fourth method. It was the optional one that allows you to do exactly that.

00:28 And that method is called __set_name__.

00:34 So __set_name__, and the first input parameter is self. The second is owner and the third one is name.

00:47 Now, what do these represent? Well, self is what it always is. That’s the instance of the StringValidator class. owner is the Song class, so that is the class from which the StringValidator class was triggered, and the name is the name of the class attribute that the descriptor class instance was assigned to.

01:08 So that is exactly what we need. So that will be title if we are validating title, and it will be artist if we’re validating the artist.

01:18 So the trick here is to create an attribute of the StringValidator class that holds the value that we need. So self, and I’m going to call that .private_name.

01:31 That will be an underscore, and then just add the value of name. So if the validation is triggered from title in the Song class, then this will be _title.

01:44 And if the validation is triggered from artist, then this will be _artist. So now that you have this attribute of StringValidator, you can just use that in the rest of the code for the .__get__() and the .__set__() methods.

02:00 So for .__get__(), instead of having the hard-coded title here, use self.private_name. And then the same thing here in your f-string.

02:11 Of course, it’s a variable, so you use curly brackets and then the same thing in the .__set__() method. So just going to quickly copy that,

02:25 replace the hard-coded attribute name here, and then the same thing here in the setattr.

02:35 Before you test this code, I would like to make one more change, which is to avoid the hard coding of minsize, and you will do that in the next lesson.

Become a Member to join the conversation.