What You Will Learn
Intermediate
- How method overriding works
- Using super() to extend parent behavior
- Method Resolution Order (MRO)
Terminalpython
class Vehicle:
def start(self):
print("Turning on engine...")
class Car(Vehicle):
def start(self):
super().start() # Call parent method first
print("Car is ready to drive!")
class ElectricCar(Car):
def start(self):
super().start() # Calls Car.start()
print("Electric motor engaged.")
tesla = ElectricCar()
tesla.start()
# Turning on engine...
# Car is ready to drive!
# Electric motor engaged.super() in __init__
Always call super().__init__() in child class constructors to ensure parent attributes are initialized. Otherwise, parent attributes will not be set.Practical Exercise
Create Vehicle.start() and Car.start()
In Car.start(): call super().start() then add behavior
Create ElectricCar(Car) that also calls super()
Test: see the chain of super() calls
Key Takeaways
- Override: redefine parent method in child.
- super() calls the parent version of the method.
- super().__init__() ensures parent attributes are set.
- MRO (Method Resolution Order): the order Python searches for methods.
- super() follows MRO - important for multiple inheritance.
Comments
Comments
Post a Comment