Python Code Example: Area of ​​a Rectangle

In object-oriented programming (OOP), we can represent real-world objects using classes and objects. A rectangle is a common geometric shape that has a length and a width, and we can define a class to model it.

In this example, we will create a Rectangle class in Python that includes:

  • Instance attributes for length and width
  • A method to calculate the area of the rectangle
  • Object instantiation and calling the area method

Python Code Example

class Rectangle:
    """Class to represent a rectangle and calculate its area."""
    
    def __init__(self, length, width):
        """Constructor to initialize length and width."""
        self.length = length
        self.width = width

    def area(self):
        """Method to calculate the area of the rectangle."""
        return self.length * self.width

# Creating a Rectangle object with length 10 and width 5
rect = Rectangle(10, 5)

# Calculating and displaying the area
print(f"The area of the rectangle is: {rect.area()}")

Expected Output

The area of the rectangle is: 50

Code Explanation

  1. Defining the Rectangle class
    • The class contains an __init__ method that initializes the length and width attributes when an object is created.
  2. Creating the area method
    • This method calculates the area using the formula: Area = length × width
  3. Creating an object of the class
    • We instantiate a Rectangle object with length = 10 and width = 5.
  4. Calling the area method
    • The area() method is called, which returns 10 × 5 = 50, and the result is printed.

Using OOP, we encapsulate data (length, width) and behavior (calculating area) in a structured way, making our code more modular and reusable! 🚀