@dataclass basics
- Python course
- Intermediate
- Lesson 53/116
- 5 min
Learn data classes with @dataclass.
@dataclass basics
The @dataclass decorator turns a class into a dataclass. From the fields you write in the body, it auto-generates the constructor, __repr__ and __eq__ methods. It is imported from the dataclasses module.
Example: @dataclass\nclass Point:\n x: int = 0\n y: int = 0. This short definition gives you the Point(x=0, y=0) call, print(p) and p1 == p2 comparison automatically. Each field name must have a type annotation; without it, the dataclass does not work.
Type annotations required
In a dataclass, each field name must come with a type. The line x: int = 0 has int as the type and 0 as the default. Without a type annotation, @dataclass does not see the field.
The type is only a hint; it is not enforced at runtime. So you can write int and later assign p.x = "text"; Python allows it. Still, writing the type correctly improves readability and tooling support.
Practice Define the Point dataclass
Start with from dataclasses import dataclass. Define a Point class with @dataclass; include fields x: int = 0 and y: int = 0. Then create an instance with p = Point(3, 4) and print with print(p.x, p.y).
Starter code
# Define the Point dataclassSample solution
# Define the Point dataclass
from dataclasses import dataclass
@dataclass
class Point:
x: int = 0
y: int = 0
p = Point(3, 4)
print(p.x, p.y)Expected output
3 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does @dataclass generate automatically?
- Only __str__
- Only __init__
- __init__, __repr__, __eq__ Correct answer
- Nothing
Explanation: @dataclass auto-generates the constructor, repr and eq methods.
2 Complete the import line
from dataclasses import ____
@dataclass
class Point:
x: int = 0
y: int = 0
from dataclasses import dataclass
@dataclass
class Point:
x: int = 0
y: int = 0
Explanation: The dataclass decorator is in the dataclasses module.
3 Match the dataclass parts
| Term | Meaning |
|---|---|
@dataclass |
Decorator |
x: int = 0 |
Field definition |
Point(3, 4) |
Instance creation |
__eq__ |
Auto comparison |