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:
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()}")
The area of the rectangle is: 50
Rectangle
class__init__
method that initializes the length
and width
attributes when an object is created.area
methodRectangle
object with length = 10
and width = 5
.area
methodarea()
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! 🚀