Python Program to Find the Area of a Rectangle Using a Class
Beginner · Classes and objects
This program defines a Rectangle class that stores a length and a breadth, with methods that work out the area and the perimeter. The area of a rectangle is length x breadth, and the perimeter is 2 x (length + breadth).
Program
rectangle_class.py
class Rectangle:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
def perimeter(self):
return 2 * (self.length + self.breadth)
def is_square(self):
return self.length == self.breadth
r1 = Rectangle(8, 5) # or: r1 = Rectangle(float(input("Length: ")), float(input("Breadth: ")))
r2 = Rectangle(6, 6)
for r in [r1, r2]:
print(f"Rectangle {r.length} x {r.breadth}")
print(" Area:", r.area())
print(" Perimeter:", r.perimeter())
print(" Is it a square?", r.is_square())
Output
Rectangle 8 x 5 Area: 40 Perimeter: 26 Is it a square? False Rectangle 6 x 6 Area: 36 Perimeter: 24 Is it a square? True
How it works
__init__stores the length and breadth inside each new object asself.lengthandself.breadth.area()andperimeter()use those stored values, so they are called with no arguments:selfis passed automatically.is_square()returnsTruewhen both sides are equal, as they are for the 6 x 6 rectangle.- The two objects come from one class but keep their own measurements, so one loop can report on both.
Another way to write it
Comparing rooms stored as objects
Comparing rooms stored as objects
class Rectangle:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
rooms = {"Bedroom": Rectangle(4, 3.5), "Kitchen": Rectangle(3, 2.5), "Hall": Rectangle(6, 4.5)}
for name, room in rooms.items():
print(f"{name}: {room.area()} square metres")
biggest = max(rooms, key=lambda name: rooms[name].area())
print("The biggest room is the", biggest)
Output
Bedroom: 14.0 square metres Kitchen: 7.5 square metres Hall: 27.0 square metres The biggest room is the Hall
Objects can be stored in a dictionary like any other value, and max() with a key function picks the room whose area is largest.
Try it yourself
Add a diagonal() method that returns (self.length ** 2 + self.breadth ** 2) ** 0.5.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises