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.
For additional information on related topics, take a look at the following resources:
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Inheritance and Composition: A Python OOP Guide (Course)
- Inheritance and Composition: A Python OOP Guide (Quiz)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- A Conceptual Primer on OOP in Python (Course)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)