Computing Area with Polymorphism

Write classes Rectangle and Triangle both having a method area(). Now write a function that can take any shape and print the area of that shape, demonstrating polymorphism.

Example 1:

Input: Rectangle with length 5 and breadth 4 
Output: "Area: 20"

Example 2:

Input: Triangle with base 5 and height 4
Output: "Area: 10"

Override the area() method in each subclass to calculate the area of the shape. Write a function that takes an instance of a shape and calls its area() method.

class Rectangle:
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

    def area(self):
        return self.length * self.breadth

class Triangle:
    def __init__(self, base, height):
        self.base = base
        self.height = height

    def area(self):
        return 0.5 * self.base * self.height

def print_area(shape):
    print(f"Area: {shape.area()}")

# Test the function
rectangle = Rectangle(5, 4)
print_area(rectangle)  # Output: Area: 20

triangle = Triangle(5, 4)
print_area(triangle)  # Output: Area: 10

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!