Python Rectangle Class Example
class / method Topic 09 Practice

Calculate area using a Rectangle class

Create a Rectangle object with width and height, then call its area() method to compute the area.

Picture this: object stores width & height

Create Rectangle(w, h). area() multiplies the stored sides.

Rectangle(w, h)store sides
→
area()w * h
→
numberreturn

Rectangle class design

A Rectangle has width and height properties. The area() method multiplies them: width × height.

Real-world use

Calculate area for architecture, game graphics, land plots, or UI layouts. Instead of writing 3 * 4 = 12 every time, wrap it in a reusable class.

UML Class Diagram

Rectangle
- w: int
- h: int
+ __init__(w, h)
+ area(): int

Computation Flow

Input
w=3, h=4
Object
rect
Method
rect.area()
Output
12

Class definition

1class Rectangle:
2def __init__(self, w, h):
3self.w = w
4self.h = h
5def area(self):
6return self.w * self.h

rect = Rectangle(3, 4)

Press "Run one step" to visualize

Usage example

1w = 3
2h = 4
3rect = Rectangle(w, h)
4print(rect.area()) # Outputs: 12