subclass | Python Glossary – Real Python

In Python, a subclass is a class that inherits from another class, known as its base class, superclass, or parent class.

When you create a subclass, you define a new class based on an existing one, which allows you to reuse code and extend functionality. This is a key feature of object-oriented programming (OOP) called inheritance, which promotes code reuse and modularity.

By inheriting from a superclass, a subclass gains access to its attributes and methods. At the same time, the subclass can override these attributes and methods, extend them, or introduce new ones. This allows for customization and specialization of the subclass. Creating subclasses is a common way to model relationships and hierarchies in programming.

Example

Here’s an example demonstrating how you can create and use a subclass in Python:

In this example, Helicopter is a subclass of Aircraft. The subclass extends the initializer method of Aircraft by adding a new attribute, .num_rotors. It also extends .show_technical_specs() by calling super() to reuse the superclass’s implementation while adding helicopter-specific details.

You can create an instance of the subclass to confirm that it inherits .fly() from the superclass and that the extended methods work as intended:

By creating a subclass based on Aircraft, you avoid duplicating generic functionality shared across different aircraft types. At the same time, you can extend or override functionality specific to helicopters.

Inheritance and Composition: A Python OOP Guide

For additional information on related topics, take a look at the following resources: