Lesson 27 of 55
PythonOOP – Polymorphism
20 minutes
Course progress49%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 27 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
Polymorphism means “many forms”. Different classes can be used interchangeably if they implement the same interface or method signature.
class Shape:
def area(self):
raise NotImplementedError
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return math.pi * self.radius ** 2
shapes = [Square(3), Circle(2)]
for s in shapes:
print('Area:', s.area())
Both Square and Circle implement area(), allowing the loop to treat them uniformly.