Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Overriding Properties in Subclasses
00:00 Overriding Properties in Subclasses. When you create Python classes that include properties and release them in a package or library, you should expect that your users do a wide variety of things with them.
00:14 One of these things could be subclassing them to customize their functionalities. In these cases, your users have to be careful and be aware of a subtle gotcha.
00:25
If you partially override a property, then you lose the non-overridden functionality. For example, suppose you are coding an Employee class to manage employee information in your company’s internal accounting system.
00:39
You already have a class called Person, and you think about subclassing it to reuse its functionality.
01:01
Person has a .name attribute implemented as a property. The current implementation of .name doesn’t meet the requirement of returning the name in uppercase letters.
01:14
Here’s how you end up solving this. In Employee, you override .name to make sure that when you access the attribute, you get the employee name in uppercase.
02:03
Employee works as you need. It returns the name using uppercase letters. However, subsequent tests uncover an unexpected behavior. You may be wondering what’s happened.
02:18 When you override an existing property from a parent class, you override the whole functionality of that property. In this example, you reimplemented the getter method only.
02:28
Because of that, .name lost the rest of the functionality from the base class. You don’t have a setter method any longer. The idea is that if you ever need to override a property in a subclass, then you should provide all of the functionality you need in the new version of the property at hand.
02:56 With this code in place, you can now set the employee’s name without issue.
03:29 Now that you’ve completed the content of the course, in the next section, you’ll review what you’ve learned.
Become a Member to join the conversation.