Python Method Overriding Explained with Examples

Python Method Overriding Explained with Examples


Want to understand Python method overriding with examples you can run right now? This beginner-friendly guide walks you through what overriding means in object-oriented programming (OOP), why it matters, and how to use it safely in your own classes. If you are new to Python classes and inheritance, you can also review the basics in our Python tutorials.

What is method overriding in Python?

Diagram of python method overriding with examples: subclass overrides base method and polymorphic calls use the child method
Subclass overriding a base method, with polymorphism in action.

Method overriding in Python happens when a subclass defines a method with the same name as a method in its parent class (base class), providing a new implementation. When you call that method on a subclass instance, Python will use the subclass version first. This is a core part of Python OOP basics and makes inheritance flexible and powerful.

  • Attribute lookup rule: Python looks for the method on the object’s class first, then walks up the inheritance chain following the method resolution order (MRO).
  • Override vs extend: You can completely replace the parent method or extend it with super().
  • Common use: Customize or specialize behavior in child classes while reusing shared logic from the parent.
Key takeaways: python method overriding with examples

  • A subclass method with the same name replaces the base method; Python follows the MRO for lookup.
  • Use super() to extend behavior so every class in the MRO can cooperate.
  • Keep parameters compatible with the parent method for predictable overrides.
  • Special (dunder) methods are resolved on the class, not the instance.

Python method overriding with examples: the simplest case

Flow of python method overriding with examples: subclass calls parent via super and then adds extra behavior
Overriding with super(): call the parent, then extend the method.

Let’s start with a very simple example of overriding a parent class method in Python.

Code
class Animal:
    def speak(self):
        return "Some generic animal sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

a = Animal()
d = Dog()

print(a.speak())
print(d.speak())
Output
Some generic animal sound
Woof!

Because Dog overrides speak(), calling d.speak() uses the new implementation. This is the essence of method overriding in Python.

Why use overriding?

  • Specialization: A subclass can customize how it behaves (e.g., a Dog speaks differently from a generic Animal).
  • Reuse: Keep shared logic in the parent, override only what’s different in the child.
  • Consistency: Create a common interface in the base class, ensure each subclass implements it in its own way.

Extending behavior with super() (not just replacing)

Often you don’t want to discard the parent’s work—you want to add to it. Use super() to call the parent method from inside the overriding method. The zero-argument form super() is the recommended Python 3 style.

Code
from datetime class="cd-package">import datetime

class Logger:
    def log(self, message):
        print(f"[LOG] {message}")

class TimestampLogger(Logger):
    def log(self, message):
        # Extend: add a timestamp, then call the parent implementation
        now = datetime.now().isoformat(timespec="seconds")
        super().log(f"{now} - {message}")

t = TimestampLogger()
t.log("System started")
Output
[LOG] 2026-09-28T12:34:56 - System started

This pattern is common when you want to override parent class methods but still leverage their original logic.

How method lookup works (MRO) in inheritance

Python uses the C3 linearization algorithm to determine the order in which classes are searched for attributes and methods. You can inspect it with Class.__mro__ or Class.mro().

Code
class A:
    def who(self):
        return "A"

class B(A):
    def who(self):
        return "B"

class C(B, A):
    pass

c = C()
print(c.who())           # Resolved in B, before A
print(C.__mro__)         # Shows the lookup order
Output
B
(<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
Visual: How a method call resolves (MRO + super())
Example MRO for Child(Left, Right):
Child
→
Left
→
Right
→
Base
→
object

Call c.go() starts at Child. Child has no go, so Python checks next in the MRO.
↓
Found Left.go(). If Left.go() uses super(), control passes to the next class in the MRO.
↓
Right.go() runs, then super() forwards to Base.go(), continuing along the MRO.

Tip: super() means “call the next implementation in the MRO,” not “call my direct parent.”

In multiple inheritance scenarios, always prefer super() inside overriding methods so that all classes in the MRO can cooperate correctly.

Python method overriding example step by step

  1. Create a base class with a method.
  2. Inherit from the base class.
  3. Define a method with the same name in the subclass.
  4. Optionally call super().method() to extend behavior.
Code
class Shape:
    def area(self):
        # Default(not meaningful), but serves as a shared interface
        return 0

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = h

    def area(self):
        # Override and compute actual area
        return self.w * self.h

rect = Rectangle(3, 4)
print(rect.area())
Output
12

How to override __init__ in a Python class

Overriding __init__ is common when a subclass needs extra attributes. If the parent __init__ sets important attributes, call it via super().__init__() to ensure the object is properly initialized.

Code
class User:
    def __init__(self, name):
        self.name = name

class Student(User):
    def __init__(self, name, grade):
        super().__init__(name)  # Call parent initializer
        self.grade = grade

s = Student("Anya", "A")
print(s.name, s.grade)
Output
Anya A

If you forget to call super().__init__() (and the parent defines critical setup), you may get missing attributes or errors later.

Overriding special (dunder) methods

Special methods like __str__, __len__, and __eq__ integrate your class with Python’s data model. Define them on the class to override behavior in a Pythonic way.

Code
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __str__(self):
        return f"({self.x}, {self.y})"

p = Point(2, 5)
print(str(p))
Output
(2, 5)

Note: Special method lookup checks the class, not the instance. Assigning p.__str__ = ... on the instance won’t affect str(p).

Multiple inheritance and cooperative overriding

In multiple inheritance, use super() to let each class in the chain contribute. Directly calling a specific parent’s method can break cooperative behavior.

Code
class Base:
    def go(self):
        print("Base.go")

class Left(Base):
    def go(self):
        print("Left.go start")
        super().go()
        print("Left.go end")

class Right(Base):
    def go(self):
        print("Right.go start")
        super().go()
        print("Right.go end")

class Child(Left, Right):
    pass

c = Child()
c.go()
print([cls.__name__ for cls in Child.mro()])
Output
Left.go start
Right.go start
Base.go
Right.go end
Left.go end
['Child', 'Left', 'Right', 'Base', 'object']

Each class uses super(), so calls flow through the full MRO.

Common mistakes when overriding (and how to fix them)

  • Changing the method’s intended meaning or signature drastically, making subclasses hard to use consistently. Fix: Keep the same method name and compatible parameters.
  • Forgetting super() when the parent sets important state (especially in __init__). Fix: Call super().__init__(...) in the subclass.
  • Calling a specific parent directly in multiple inheritance (e.g., Parent.method(self)). Fix: Prefer super() for cooperative MRO-aware calls.
  • Expecting runtime “overloading” by different parameter types or counts. Python doesn’t do that at runtime. Fix: Use default parameters, *args/**kwargs, or type-checker-only @overload annotations if you use typing.
  • Defining special methods on instances and expecting them to work. Fix: Define __str__, __len__, etc., on the class.

Difference between method overriding and overloading in Python

These terms are easy to mix up. Here’s the short comparison:

Concept Method Overriding Method Overloading
Where it happens Between classes (subclass redefines parent method) In the same class (same method name, different parameter lists)
Runtime behavior in Python Supported directly via inheritance and MRO Not supported by parameter types/count at runtime
Typical Python approach Define the method in subclass; optionally use super() Use default args, *args/**kwargs, or @overload for type checkers only
Example Dog.speak() replaces Animal.speak() One area() that accepts different kinds of inputs via optional args

Modern tips: typing helpers for safer overriding

As you grow beyond the basics, type hinting can make overrides safer and clearer (checked by tools like mypy or pyright):

  • @typing.override (Python 3.12+): Marks that a method is intended to override a parent method. Type checkers can alert you if the parent has no such method or the signature is incompatible. It does not change runtime behavior.
  • @typing.final (Python 3.8+): Mark a method or class that should not be overridden or subclassed. Enforced by type checkers.
  • typing.Self (Python 3.11+): Annotate methods that return the current instance (useful for fluent APIs) so overrides remain type-accurate.

Practice: try a quick override yourself

  1. Create a base class Vehicle with a move() method returning a generic string.
  2. Create subclasses Car and Bicycle that override move().
  3. In one subclass, extend the behavior with super() if you keep shared work in the base.

Small hands-on challenges like this build confidence with method overriding in Python for beginners.

FAQ: People also ask

What is method overriding in Python with a simple example?

It’s when a subclass provides a new implementation for a method defined in its parent. Example:

Code
class Parent:
    def greet(self):
        return "Hello from Parent"

class Child(Parent):
    def greet(self):
        return "Hello from Child"

print(Child().greet())
Output
Hello from Child

How do I override a method in Python step by step?

  1. Define the parent class and its method.
  2. Create a subclass inheriting from the parent.
  3. Define a method with the same name in the subclass.
  4. If needed, call super().method() inside the subclass method to extend the parent’s behavior.

When should I use super() while overriding a method in Python?

Use super() when the parent class performs important work you still want to run—such as initializing attributes in __init__ or contributing part of a larger operation. In multiple inheritance, super() respects the MRO so all classes can cooperate.

Can we override __init__ in Python and how does it work?

Yes. Define __init__ in the subclass. If the parent __init__ sets necessary attributes, call super().__init__(...) to ensure proper initialization.

What is the difference between method overriding and overloading in Python?

Overriding replaces a parent method in a subclass at runtime (fully supported). Overloading by different parameter lists is not a runtime feature in Python; instead, use defaults, *args/**kwargs, or type-checker-only @overload hints.

Quick checklist before you ship




Related Python tutorials

Continue learning Python OOP basics, classes, and inheritance in our main Python path: CodDesire Python Tutorials.

Sources / Further reading

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted