Polymorphism & Method Overriding

Polymorphism means "many forms". In OOP, the same method name can behave differently depending on which class's object you call it on. This lets you write code that works on a collection of related objects without knowing their exact types.

Method Overriding

When a child class defines a method with the same name as the parent, the child's version overrides the parent's. Python always calls the most specific version.

class Shape:
    def area(self): return 0
class Rectangle(Shape):
    def area(self): return self.width * self.height
class Circle(Shape):
    def area(self): return math.pi * self.radius ** 2

Calling Methods Polymorphically

shapes = [Rectangle(4, 5), Circle(3), Rectangle(2, 8)]
for s in shapes:
    print(s.area())  # Python picks the right area() each time
20
28.274...
16

The loop does not need to know whether each shape is a Rectangle or Circle. Python resolves the correct method at runtime — this is runtime dispatch.

Real-World Examples

  • GUI toolkit: TextInput, PasswordInput, DateInput all inherit from Input but render() differently
  • Game bots: AggressiveBot, DefensiveBot inherit from Bot but choose_move() returns different strategies
  • IB exam: questions often ask you to draw a class hierarchy and explain how polymorphism enables a single loop to process mixed object types

Your Task

  1. In Rectangle.area(), return self.width * self.height
  2. In Circle.area(), return math.pi * self.radius ** 2
  3. The shapes loop at the bottom should print the correct area for each shape

Expected: Rectangle(4,5) → 20.00, Circle(3) → 28.27

Section 1/4Method Overriding

Method Overriding

When a child class defines a method with the same name as the parent, the child's version overrides the parent's. Python always calls the most specific version.

Polymorphism & Method Overriding

Polymorphism means "many forms". In OOP, the same method name can behave differently depending on which class's object you call it on. This lets you write code that works on a collection of related objects without knowing their exact types.

Method Overriding

When a child class defines a method with the same name as the parent, the child's version overrides the parent's. Python always calls the most specific version.

class Shape:
    def area(self): return 0
class Rectangle(Shape):
    def area(self): return self.width * self.height
class Circle(Shape):
    def area(self): return math.pi * self.radius ** 2

Output:

Click "Check" to run your code.