A First Look at Inheritance
Introduction
Welcome back to Sharing Behavior Between Classes in Python. We are now beginning Unit 2 of 3. In the previous lesson, we learned how class variables let every object of a class share the same data, while instance variables keep each object's data separate. Now we will explore a different kind of sharing: one class can inherit the methods and logic of another.
In this lesson, we will learn how to:
- Describe the "is-a" relationship between a subclass and its parent class.
- Define a base class and declare a subclass that starts empty.
- Call an inherited method on a subclass instance without redefining it.
- Use
super().__init__()in a subclass constructor to reuse the parent's setup. - Confirm the relationship with
isinstance.
The "is-a" Relationship
When one class is a specialized version of another, we say the specialized class is a kind of the general class. A motorcycle is a vehicle. It shares the idea of a model and wheels, but it also has details of its own — like whether it carries a sidecar.
In Python, we express this by defining a subclass (also called a child class) that inherits from a base class (also called a parent class). The subclass inherits access to the parent's methods, and each object receives its instance attributes when an initialization constructor executes.
Define a Base Class with a Constructor and Method
We begin with the general class. Our Vehicle stores a model name and a wheel count, and provides a describe() method:
The constructor sets two instance attributes, and describe() returns a readable summary. This is the behavior every vehicle should share.
Declare a Subclass That Inherits Everything
To declare a subclass, we put the parent class name in parentheses after the new class name:
The pass statement means the subclass body is empty for now. Even so, Motorcycle automatically uses the inherited Vehicle.__init__ and describe methods. We can create a motorcycle using the exact same parameters the parent expects:
