Create a class Shape and then define child classes Square, Circle, Triangle, each with appropriate methods for calculating area. The Square class takes the side length, the Circle class takes the radius, and the Triangle class takes the base and height.
Example 1:
Input: Square(5) Output: 25
Example 2:
Input: Triangle(3, 4) Output: 6
Use the appropriate formulas for calculating the area of each shape: Square (side^2), Circle (π * radius^2), Triangle (0.5 * base * height).
import math
class Shape:
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 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
square = Square(5)
print(square.area()) # Output: 25
triangle = Triangle(3, 4)
print(triangle.area()) # Output: 6
Unlock AI & Data Science treasures. Log in!