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

Unlock This Lesson

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

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Inheritance and Subclassing

00:00 Inheritance. You can subclass data classes quite freely. As an example, we’ll extend our Position data class with a country field to record capitals.

00:37 In this simple example, everything works without a hitch. The country field of Capital is added after the three original fields in Position. Things get a little more complicated if any fields in the base class have default values.

01:25 This code will generate a TypeError complaining that non-default argument 'country' follows default argument. The problem is that our new country field has no default value, while the lon and lat fields have default values.

01:41 The data class will try and write the code seen onscreen, and this is not valid Python. If a parameter has a default value, all following parameters must also have default values.

01:55 In other words, if a field in a base class has a default value, then all new fields added in a subclass must have default values as well. Another thing to be aware of is how fields are ordered in a subclass.

02:09 Starting with the base class, fields are ordered in the order in which they are first defined. If a field is redefined in a subclass, its order doesn’t change. For example, if you define Position and Capital as seen onscreen,

02:52 then the order of the fields in Capital will still be name, lon, lat, country. However, the default value of lat will be 40.0.

03:11 In the next section of the course, you’ll take a look at how to make data classes faster and use less memory.

user45755 on Sept. 29, 2021

Lost me at the end

Bartosz Zaczyński RP Team on Sept. 29, 2021

@user45755 Feeling lost is a good sign. It means that you’re learning 😉 Which part of the lesson did you find problematic, specifically?

Become a Member to join the conversation.