Editor

Rectangle with Computed Area

Intermediate · Write the code · from Python Dataclasses: Less Boilerplate, More Readable Code

From the lesson: Python Dataclasses: Less Boilerplate, More Readable Code

Imagine filling out a form where you have to write your name, address, and phone number. Now imagine filling out 50 forms where every single one asks for the same information in a slightly different format. That's what writing Python classes feels like sometimes.

Read the lesson

Create a dataclass called Rectangle with width (float), height (float), and area (float, default 0.0). Use __post_init__ to compute area as width * height automatically. Create a rectangle with width 5.0 and height 3.0, then print its area.

from dataclasses import dataclass
# Create Rectangle with __post_init__

More Dataclass exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz