Python Practice › OOP Programs › Program 37

Shape with Square and Triangle

EasyOOP Programs · 37 of 48

Create a Shape class with an area method and subclasses Square and Triangle.

Advertisement
Output
Square 16
Triangle 9.0

Approach

  1. Each subclass overrides area().

Solution

Python
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.

More oop programs

← All 48 OOP Programs

Leave a Comment