Dataclasses
The @dataclass decorator writes __init__, __repr__ and __eq__ for you from a list of typed fields. It is ideal for classes that mostly just hold data. Use field(default_factory=list) for mutable defaults.
Example
from dataclasses import dataclass, field
@dataclass
class Course:
title: str
lessons: int = 0
tags: list = field(default_factory=list)
c = Course("Python", 70)
c.tags.append("beginner")
print(c)
print(c == Course("Python", 70, ["beginner"]))Result
Course(title='Python', lessons=70, tags=['beginner']) True
Exercise
Import the decorator.
from dataclasses import Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.