Skip to content
dreamcode
dreamcode
Map
Dataclasses
Lesson 47 of 77
+15 XP on finish
OBJECTSChapter 8 · Objects and Classes

Data classes

@dataclass writes the repetitive parts of a class for you: __init__, a readable __repr__ and __eq__, all generated from the field annotations. Give a field a default with =, and use field(default_factory=list) when each object needs its own fresh list.

Worked example

How it reads

  • Each name: type line becomes a constructor parameter
  • The generated __repr__ prints every field
  • The generated __eq__ compares field by field
Common mistakes
  • tags: list = [] is rejected: a shared list default would be the same list for every object. Use field(default_factory=list).
Cloud tip: Add frozen=True (@dataclass(frozen=True)) for objects that should never change after they are made.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Rewrite Planet as a @dataclass with fields name: str and moons: int, then print Planet("Mars", 2) to show Planet(name='Mars', moons=2).

Press Run to check your work.