Python

Python Basics

Data Structures in Python

Control Flow and Loops

Functions and Scope

Object-Oriented Programming (OOP)

Python Programs


Method Overriding and super() in Python

Object-Oriented Programming (OOP) is one of the most important paradigms in Python. If you’ve already explored basic concepts like classes and inheritance, it’s time to take it a step further and learn how to override methods and use the built-in super() function.

These features allow child classes to modify or extend the behavior of parent classes, making your code more flexible and powerful.

In this guide, we’ll explore:

  • What method overriding is,
  • Why it’s useful,
  • How to use super() effectively,
  • And practical examples that bring these ideas to life.

Let’s get started.


What Is Method Overriding in Python?

Method overriding happens when a child class defines a method with the same name as a method in its parent class. When you create an object of the child class, the overridden method in the child class gets called instead of the one in the parent.

This is Python’s way of allowing you to customize or replace inherited behavior.


Basic Example of Method Overriding

class Animal:
def speak(self):
return "The animal makes a sound"
class Dog(Animal):
def speak(self):
return "The dog barks"
animal = Animal()
dog = Dog()
print(animal.speak()) # Output: The animal makes a sound
print(dog.speak()) # Output: The dog barks

Here, both classes have a speak() method, but the one in the child class (Dog) overrides the one from the parent class (Animal).


Why Use Method Overriding?

  • Customization: You can change how inherited methods behave for specific subclasses.
  • Polymorphism: It allows you to write general code that works with different class types.
  • Extensibility: Makes your code flexible and scalable as your project grows.

How Python Resolves Method Calls

Python uses a rule called Method Resolution Order (MRO). When you call a method on an object, Python looks for it in the object’s class first. If it’s not found, it checks the parent class, and so on.

When you override a method, Python simply finds and uses the version in the child class before it even reaches the parent.


Using super() in Python

Sometimes, while overriding a method, you still want to keep some behavior from the parent class. This is where the super() function comes in.

The super() function allows you to call the parent class’s version of a method from the child class.


Basic Example of super()

class Animal:
def speak(self):
return "The animal makes a sound"
class Dog(Animal):
def speak(self):
original_sound = super().speak()
return f"{original_sound} and the dog barks"
dog = Dog()
print(dog.speak())

Output:

The animal makes a sound and the dog barks

Here, the child class Dog extends the behavior of the parent method instead of replacing it entirely.


How super() Works Behind the Scenes

  • It returns a proxy object that delegates method calls to a parent or sibling class.
  • Works especially well in multiple inheritance.
  • Ensures your code respects Python’s Method Resolution Order (MRO).

Example: Constructor Overriding with super()

super() is often used in constructors (__init__) when you want a child class to initialize both its own attributes and those from the parent.

class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, student_id):
super().__init__(name) # Call parent constructor
self.student_id = student_id
s = Student("Alice", "S123")
print(s.name) # Alice
print(s.student_id) # S123

This approach avoids repeating code and ensures consistent initialization across classes.


Real-World Analogy

Imagine a generic Vehicle class with a start_engine() method. Now, you create a Car class that overrides this method to add “seatbelt check” before starting. But you still want the original engine-starting logic too. That’s where super() shines.


Advanced Example: Logging Activity Using super()

class Logger:
def log(self, message):
print(f"Log: {message}")
class FileLogger(Logger):
def log(self, message):
super().log(message)
print(f"Writing '{message}' to a file...")
logger = FileLogger()
logger.log("System started")

Output:

Log: System started
Writing 'System started' to a file...

This shows how you can layer behavior—log to the console and then to a file—all using super().


Best Practices

  1. ✅ Use super() for cleaner and safer inheritance.
  2. ✅ Always override only when necessary.
  3. ❌ Don’t override methods just for the sake of it—prefer clarity.
  4. ✅ Use descriptive method names in child classes when you don’t intend to override.

Common Mistakes and How to Avoid Them

MistakeWhy It’s a ProblemFix
Forgetting super() in __init__()Parent class attributes won’t initializeAlways call super().__init__()
Calling super() incorrectly in multiple inheritanceCan break MROFollow Python’s MRO and class hierarchy
Overriding method without extending needed behaviorMight lose important functionalityUse super() to preserve parent behavior

Method Overriding vs Method Overloading

ConceptPython SupportDescription
Method Overriding✅ YesSame method name in child class
Method Overloading❌ Not directlyPython does not support true overloading; use default args instead

Conclusion

Understanding method overriding and how to use super() is crucial for writing efficient and maintainable Python code. These features allow you to:

  • Customize inherited behavior,
  • Avoid code duplication,
  • And build flexible class hierarchies.

Whether you’re building a school management system, a game, or a payment platform, these concepts help you stay organized and keep your logic clean.

So next time you create a subclass in Python, ask yourself:

“Do I need to override this method? And should I call the parent’s version with super()?”

Once you get the hang of it, you’ll wonder how you ever wrote OOP code without it!