Python 6.2Code walkthrough7 parts

Dataclasses

Define a class that mainly holds data in a few lines, with type hints.

Loading your progress…Next: 6.3 The Estimator Pattern

In this lesson7 parts

  1. 01The lines we wrote by hand
  2. 02`@dataclass`
  3. 03Methods and type hints
  4. 04Defaults, and the list default
  5. 05Frozen dataclasses
  6. 06Reviews from the file
  7. 07Recap, your challenge, and next

Key terms

The words this lesson introduces, each in one line. The module’s glossary collects them all.

dataclass
A class whose __init__, __repr__ and __eq__ are written from its list of fields, with @dataclass.
decorator
A function applied to the class or function below it, written with @: @dataclass.
field
One attribute a dataclass lists, with a type hint: rating: int.
frozen
A dataclass whose objects can not be changed after they are created, @dataclass(frozen=True). Frozen objects are hashable.

Quiz 5 questions

Your first pick on each question is the one that counts, and a right one earns a coin. Getting one wrong here is how the lesson sticks.

Practice

Problems to solve in your own notebook. Each states the problem, not the steps: working out the steps is the exercise. Level A applies the lesson, B combines it with earlier ones, C stretches it.

The self-checking notebook for this lesson is Notebook 1 · Classes and Dataclasses.

Common mistakes

What you will see when it goes wrong, why it happens, and the fix.

Where it’s used

Where this lesson’s ideas turn up in real work.