25. Problem to calculate area of rectangle using class in Python

In this Python oops program, we will create an example to calculate area of rectangle using class in Python. This code demonstrates the basic functionality of the Rectangle class, allowing you to create rectangle objects, calculate their area and perimeter, and retrieve the results.

Area of rectangle using class in Python

Steps to solve the program
  1. The code defines a class named Rectangle with a constructor method __init__. The constructor takes two parameters: length and width. Inside the constructor, the values of length and width are assigned to the instance variables self.length and self.width, respectively.
  2. The class also defines two additional methods: calculate_area and calculate_perimeter. The calculate_area method calculates the area of the rectangle by multiplying the length and width, and returns the result. The calculate_perimeter method calculates the perimeter of the rectangle using the formula 2 * (length + width), and returns the result.
  3. An object of the Rectangle class is created by calling the constructor with the arguments 5 and 13. The rectangle variable now refers to this object.
  4. The calculate_area method is called on the rectangle object and the result is stored in the area variable.
  5. The calculate_perimeter method is called on the rectangle object and the result is stored in the perimeter variable.
  6. The area and perimeter are then printed using the print function.
				
					class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
    
    def calculate_area(self):
        return self.length * self.width
    
    def calculate_perimeter(self):
        return 2 * (self.length + self.width)

# Create an object of the Rectangle class
rectangle = Rectangle(5, 13)
area = rectangle.calculate_area()
perimeter = rectangle.calculate_perimeter()
print("Area:", area)
print("Perimeter:", perimeter)
				
			

Output:

				
					Area: 65
Perimeter: 36
				
			

Related Articles

Python oops program with encapsulation.

Create a Python class called Circle with attributes radius.

Leave a Comment