Python Program to Find the Area of a Rectangle Using Classes

PythonServer Side ProgrammingProgramming

When it is required to find the area of a rectangle using classes, object oriented method is used. Here, a class is defined, attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to find the area of rectangle.

Below is a demonstration for the same −

Example

 Live Demo

class shape_rectangle():
def __init__(self,my_length, my_breadth):
   self.length = my_length
   self.breadth = my_breadth
def calculate_area(self):
   return self.length*self.breadth
len_val = 6
bread_val = 45
print("The length of the rectangle is : ")
print(len_val)
print("The breadth of the rectangle is : ")
print(bread_val)
my_instance = shape_rectangle(len_val,bread_val)
print("The area of the rectangle : ")
print(my_instance.calculate_area())
print()

Output

The length of the rectangle is :
6
The breadth of the rectangle is :
45
The area of the rectangle :
270

Explanation

  • A class named ‘shape_rectangle’ is defined.
  • It has the ‘init’ method that initializes values.
  • It also has a method that calculates the area of the rectangle given the specific parameters.
  • An instance of this class is created.
  • The function to calculate area is called by passing required parameters.
  • It is displayed as output on the console.
raja
Published on 11-Mar-2021 12:52:06
Advertisements