Labs ICT
Pro Login

Polymorphism

1 min read | Python Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Polymorphism

Polymorphism lets different classes define methods with the same name but different behavior.

Method Overriding

A child class can override a method from its parent.

class Shape:
    def area(self):
        return 0

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

    def area(self):
        return 3.14 * self.radius ** 2

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

shapes = [Circle(5), Square(4)]
for s in shapes:
    print(s.area())

Duck Typing

"If it walks like a duck and quacks like a duck, it's a duck." Python cares about behaviour, not type.

class Duck:
    def sound(self):
        return "Quack"

class Car:
    def sound(self):
        return "Beep"

def make_sound(obj):
    print(obj.sound())

make_sound(Duck())
make_sound(Car())