BeginnerCoder

Lesson 16 — Dataclasses

Clean data objects

@dataclass writes the boring parts of a class for you. You list the fields with type annotations (name: str), and Python generates init and a readable repr from them. Fields are filled in the order you declare them.

from dataclasses import dataclass
@dataclass
class Point:
    x: int
    y: int
print(Point(1, 2))  # Point(x=1, y=2)

Why it matters: most programs pass around simple records, and dataclasses make them short and easy to debug.

Want it another way?
Task

Add a price field of type float to Product and print an instance.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Python Intermediate

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.