Python Practice › OOP Programs › Program 37
Shape with Square and Triangle
Create a Shape class with an area method and subclasses Square and Triangle.
Output
Square 16 Triangle 9.0
Approach
- Each subclass overrides
area().
Solution
class Shape: def area(self): raise NotImplementedError class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 class Triangle(Shape): def __init__(self, base, height): self.base, self.height = base, height def area(self): return 0.5 * self.base * self.height for shape in [Square(4), Triangle(6, 3)]: print(type(shape).__name__, shape.area())Output
Square 16 Triangle 9.0
Learn the concept
New to this topic? Read the lesson, then come back.