Calculating Area with Polymorphism

Create a class Shape with a method area(). Now extend this class into children classes Circle, Square, and Triangle, each implementing the area() method appropriately.

Example 1:

Input: Circle with radius 5 
Output: 78.54

Example 2:

Input: Square with side 5
Output: 25

Override the area() method in each subclass to calculate the area based on the shape.

import math

class Shape:
    def area(self):

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * (self.radius ** 2)

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 = base
        self.height = height

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

# Test the classes
circle = Circle(5)
print(circle.area())  # Output: 78.53981633974483

square = Square(5)
print(square.area())  # Output: 25

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!