Python Program to Find the Area of a Rectangle Using Classes
In this example, we will write a python program to find the area of a rectangle using class and objects. To better understand this example, make sure you have knowledge of the following tutorials:-
Python Program to Find the Area of a Rectangle Using Classes
class Rectangle: def __init__(self, length, breadth): self.length = length self.breadth = breadth def area(self): return self.length * self.breadth a = int(input("Enter length of rectangle: ")) b = int(input("Enter breadth of rectangle: ")) obj = Rectangle(a, b) print("Area of rectangle:", obj.area())
The output of the above program is:-
Enter length of rectangle: 30
Enter breadth of rectangle: 12
Area of rectangle: 360
Enter breadth of rectangle: 12
Area of rectangle: 360
Program Explanation
Here we have created a class named “Rectangle” that has two attributes length and breadth. The constructor of the class initiates these two attributes using __init__ function. A method “area” is created to calculate the area of the given rectangle, which basically multiplies the length and breadth of the rectangle. Once the class has been defined, we take inputs from the user as a and b where a is the length of the rectangle and b is the breadth of the rectangle. An instance of the class “Rectangle” is created as “obj” and the method is invoked to display the result..