Locked learning resources

You must own this product to watch this lesson.

Locked learning resources

You must own this product to watch this lesson.

Inheritance and Subclassing

This lesson is part of a Real Python video course by Darren Jones.

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.

You must own this product to join the conversation.