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.hCalling 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() automaticallyPolymorphism in Action
shapes = [Circle(5), Rectangle(3, 4), Circle(2)]
for shape in shapes:
print(shape.describe()) # correct area() called for each type