Method Overriding

Let a child class replace a parent's method with its own version.

Introduction

What if the child wants to do something differently from the parent? Method overriding lets a child class replace a parent's method with its own version. The method name stays the same, but the behavior changes.

The Concept

When a child defines a method with the same name as a parent method, the child's version takes over. Python uses the child's version when you call the method on a child object.

class Animal:
    def speak(self):
        print("Some generic sound")

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

class Cat(Animal):
    def speak(self):
        print("Meow!")

animals = [Dog(), Cat(), Animal()]
for a in animals:
    a.speak()
# Woof! Woof!
# Meow!
# Some generic sound

Each class has its own version of speak(). Python picks the right one based on the object's actual type.

When to Override

Override a method when the child needs different behavior for the same action. Common scenarios:

  • Different animals make different sounds -- same method name, different output.
  • Different payment methods process transactions differently.
  • Different employee types calculate bonuses with different formulas.

Partial Override (Extending)

Sometimes you do not want to completely replace the parent's method -- you want to extend it. Use super() to call the parent's version and add to it.

class Employee:
    def __init__(self, name):
        self.name = name

    def describe(self):
        return f"Employee: {self.name}"

class Manager(Employee):
    def __init__(self, name, team_size):
        super().__init__(name)
        self.team_size = team_size

    def describe(self):
        base = super().describe()
        return f"{base}, manages {self.team_size} people"

m = Manager("Alice", 5)
print(m.describe())
# Employee: Alice, manages 5 people

Key idea: A partial override keeps the parent's logic and adds more on top. A full override completely replaces the parent's logic.

OOP Terms

  • Method Overriding: When a child class redefines a method that already exists in the parent class.
  • Full Override: The child completely replaces the parent's method.
  • Partial Override: The child calls the parent's method via super() and extends it.

Real-World Connection

Think of payment processing. A Payment class might define a process() method. But CreditCard.process() and PayPal.process() work very differently under the hood. Same interface, different implementations.

Best Practices

  • Keep the same method signature (name and parameters) when overriding.
  • Prefer partial overrides when you want to add to the parent's behavior, not replace it.
  • Document why the override is necessary if the behavior change is not obvious.

Common Mistakes

  • Misspelling the method name -- Python will treat it as a new method, not an override.
  • Forgetting super() when you want a partial override -- you will lose the parent's logic entirely.
  • Changing the return type unexpectedly -- if the parent returns a string, the child should too.

Practice Exercises

  1. Create a Shape class with an info() method that returns "I am a shape". Create Circle and Square children that override info() with their own messages.
  2. Create a Vehicle class with a fuel_type() method returning "Unknown". Override it in ElectricCar to return "Electric" and in GasCar to return "Gasoline".
  3. Create a Person class with a greet() method. Create a FormalPerson that does a partial override, calling super().greet() and adding "Pleased to meet you."

Summary

  • Method overriding lets a child class redefine a parent's method with its own behavior.
  • Python automatically uses the child's version when called on a child object.
  • Use super() for partial overrides to extend rather than replace the parent's logic.
  • The method name must match exactly for the override to work.