37. Problem to create a shape class in Python

In this Python oops program, we will create a shape class in Python. Python class called Shape with a method to calculate the area of the shape.

Create a shape class in Python

Steps to solve the program
  1. The Shape class in Python is defined as a base class. It has a method calculate_area, which is left undefined (implemented as pass). This method will be overridden in the derived classes.
  2. The Square class is derived from the Shape class. It has a constructor method __init__ that takes the side_length as a parameter and initializes the instance variable self.side_length.
  3. The class overrides the calculate_area method inherited from the Shape class. It calculates the area of a square by multiplying the side_length by itself (side_length ** 2).
  4. The Triangle class is derived from the Shape class. It has a constructor method __init__ that takes the base and height as parameters and initializes the instance variables self.base and self.height.
  5. The class overrides the calculate_area method inherited from the Shape class. It calculates the area of a triangle using the formula 0.5 * base * height.
  6. The code creates objects square and triangle of the Square and Triangle classes, respectively, by passing the required parameters to their constructors.
  7. The calculate_area method is called on each object, and the calculated areas are printed.
				
					class Shape:
    def calculate_area(self):
        pass

class Square(Shape):
    def __init__(self, side_length):
        self.side_length = side_length
    
    def calculate_area(self):
        return self.side_length ** 2

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height
    
    def calculate_area(self):
        return 0.5 * self.base * self.height

# Create objects of the Square and Triangle classes
square = Square(5)
triangle = Triangle(4, 6)
print("Square Area:", square.calculate_area())
print("Triangle Area:", triangle.calculate_area())
				
			

Output:

				
					Square Area: 25
Triangle Area: 12.0
				
			

Related Articles

Create a Python class called Course with attributes name, teacher, and students.

Create a Python class called Employee with attributes name and salary.

Leave a Comment