Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Module 5 - Object-Oriented Programming Python Python OOP Python Programming: From Zero to Real-World Applications

Method Overriding and super() in Python

Reviewed & accurate
AI Summary

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.
Previously: Lesson 33 covered inheritance.
Today: You learned: Override methods and use super() effectively.
Next: Lesson 35 covers encapsulation.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments