Call parent or next-in-MRO implementations using super().
How It Works
super() gives access to the next method in a class’s method resolution order, not necessarily a single fixed parent. It helps subclasses extend initialization or method behavior cooperatively.
super() matters especially in cooperative multiple-inheritance designs.
Step-by-Step Example
class Vehicle:
def __init__(self, vehicle_name):
self.vehicle_name = vehicle_name
class ElectricVehicle(Vehicle):
def __init__(self, vehicle_name, battery_percent):
super().__init__(vehicle_name)
self.battery_percent = battery_percent
vehicle = ElectricVehicle("City Car", 85)
print(vehicle.vehicle_name, vehicle.battery_percent)
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
City Car 85
Where This Fits in a Real Program
Before putting the technique into a larger program, identify the required inputs and which results are returned. Choose what should happen with invalid or missing data, and test a small valid case and a failing case independently.
Practice: Try It Yourself
Extend a base class initializer while preserving its required setup.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Calling super().__init__() with arguments that do not match the parent initializer.
- Assuming super() always means call one manually selected direct parent.
Key Takeaways
- Call parent or next-in-MRO implementations using super().
- super() gives access to the next method in a class’s method resolution order, not necessarily a single fixed parent.
- super() matters especially in cooperative multiple-inheritance designs.