Lesson 27 of 55 · Python
OOP – Polymorphism
Duration: 20 minutes
Lesson 27 of 55 · Python
Duration: 20 minutes
python\nclass Shape:\n def area(self):\n raise NotImplementedError\n\nclass Square(Shape):\n def __init__(self, side):\n self.side = side\n def area(self):\n return self.side * self.side\n\nclass Circle(Shape):\n def __init__(self, radius):\n self.radius = radius\n def area(self):\n import math\n return math.pi * self.radius ** 2\n\nshapes = [Square(3), Circle(2)]\nfor s in shapes:\n print('Area:', s.area())\n\n\nBoth Square and Circle implement area(), allowing the loop to treat them uniformly.\n