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
- 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.
- 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.
- 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).
- 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.
- 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.
- The code creates objects square and triangle of the Square and Triangle classes, respectively, by passing the required parameters to their constructors.
- 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 Employee with attributes name and salary.
Create a Python class called Manager that inherits from the Employee class.
Create a Python class called Customer with attributes name and balance.
Create a Python class called VIPCustomer that inherits from the Customer class.
Create a Python class called Phone with attributes brand, model, and storage.
Create a Python class called Laptop with attributes brand, model, and storage.