SyntaxStudy
Sign Up
Python Intermediate 9 min read

Method Overriding

Method Overriding

A child class can replace a parent's method by defining a method with the same name. You can still call the parent version using super().

Basic Override

class Shape:
    def area(self):
        return 0

    def describe(self):
        return f"I am a {type(self).__name__} with area {self.area():.2f}"

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):              # override
        import math
        return math.pi * self.radius ** 2

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

    def area(self):              # override
        return self.w * self.h

Calling the Parent Method

class LoggedRectangle(Rectangle):
    def area(self):
        result = super().area()   # call Rectangle.area()
        print(f"area() called → {result}")
        return result

lr = LoggedRectangle(3, 4)
print(lr.describe())   # calls overridden area() automatically

Polymorphism in Action

shapes = [Circle(5), Rectangle(3, 4), Circle(2)]
for shape in shapes:
    print(shape.describe())   # correct area() called for each type
Example
class Logger:
    def log(self, msg):
        print(f"[LOG] {msg}")

class TimestampLogger(Logger):
    def log(self, msg):
        from datetime import datetime
        ts = datetime.now().strftime("%H:%M:%S")
        super().log(f"{ts} - {msg}")

class PrefixLogger(TimestampLogger):
    def __init__(self, prefix):
        self.prefix = prefix

    def log(self, msg):
        super().log(f"[{self.prefix}] {msg}")

pl = PrefixLogger("APP")
pl.log("Server started")
pl.log("User logged in")
Pro Tip

Method overriding enables polymorphism — the same code (a loop over shapes) can work correctly with many different types as long as they share the same interface.