Tsallaka zuwa abun ciki
Justice Tech School

Polymorphism

Polymorphism means that different classes can offer the same method, so code can call it without caring about the exact class. Python also uses duck typing: if an object has the method you need, it works.

Example
class Circle:
    def __init__(self, r):
        self.r = r
    def area(self):
        return round(3.14159 * self.r ** 2, 2)

class Square:
    def __init__(self, s):
        self.s = s
    def area(self):
        return self.s ** 2

for shape in [Circle(2), Square(3)]:
    print(type(shape).__name__, shape.area())

Result

Circle 12.57
Square 9

Exercise

Call the shared method on each shape.

for s in shapes:
    print(s.())

Quiz Test

What is the idea of polymorphism?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.