Skip to the content

dataclass

Python · Unit 14: Modern classes

Lots of classes only hold data, and their __init__ always does the same thing: take a value and copy it into self.

@dataclass writes that __init__ for you. You import it from dataclasses, put it above the class, and list the fields with their type inside.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(3, 4)
print(p.x, p.y)

Prints

3 4

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Complete it so Python writes the __init__ for Mug.

  2. 2. Predict the output

    What does this code print?

  3. 3. Predict the output

    What does this code print?

  4. 4. Complete the code

    Complete it so the ticket stores its price. It should print: 150 True

  5. 5. Find the bug

    This program should print Rex 5. Which line has the error?

  6. 6. Predict the output

    What does this code print?

  7. 7. Complete the code

    Complete it so every shopping list starts out empty.

  8. 8. Multiple choice

    Why isn't players: list = [] allowed in a @dataclass?

  9. 9. Put the lines in order

    Put the lines in order so it prints: Math 10

  10. 10. Predict the output

    Pricey fruit is anything over 20. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →