Python Program to Find the Area of a Rectangle Using Classes

When working with object-oriented programming in Python, we can create a class to represent geometric shapes and calculate their properties. This example demonstrates how to find the area of a rectangle using a class with attributes and methods.

Below is a demonstration for the same −

Example

class RectangleShape:
    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 = RectangleShape(len_val, bread_val)
print("The area of the rectangle:")
print(my_instance.calculate_area())

Output

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

Enhanced Example with Input Validation

Here's an improved version with input validation and better formatting ?

class Rectangle:
    def __init__(self, length, breadth):
        if length <= 0 or breadth <= 0:
            raise ValueError("Length and breadth must be positive values")
        self.length = length
        self.breadth = breadth
    
    def calculate_area(self):
        return self.length * self.breadth
    
    def display_info(self):
        print(f"Rectangle: {self.length} x {self.breadth}")
        print(f"Area: {self.calculate_area()} square units")

# Create rectangle instance
rectangle = Rectangle(8, 12)
rectangle.display_info()
Rectangle: 8 x 12
Area: 96 square units

How It Works

  • A class named Rectangle is defined with proper naming convention
  • The __init__ method initializes the length and breadth attributes
  • The calculate_area() method returns the product of length and breadth
  • An instance of the class is created with specific dimensions
  • The area calculation method is called and the result is displayed
  • Input validation ensures only positive values are accepted

Key Benefits of Using Classes

  • Encapsulation: Data (length, breadth) and methods are bundled together
  • Reusability: Multiple rectangle objects can be created with different dimensions
  • Maintainability: Easy to modify or extend the Rectangle class

Conclusion

Using classes to calculate rectangle area provides better code organization and reusability. The object-oriented approach allows easy creation of multiple rectangle instances with different dimensions while maintaining clean, structured code.

Updated on: 2026-03-25T17:22:43+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements