dataclass
Python · Unit 14: Modern classes
- Full plan
- Python
- 10 exercises
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. Complete the code
Complete it so Python writes the
__init__forMug.2. Predict the output
What does this code print?
3. Predict the output
What does this code print?
4. Complete the code
Complete it so the ticket stores its price. It should print: 150 True
5. Find the bug
This program should print Rex 5. Which line has the error?
6. Predict the output
What does this code print?
7. Complete the code
Complete it so every shopping list starts out empty.
8. Multiple choice
Why isn't
players: list = []allowed in a@dataclass?9. Put the lines in order
Put the lines in order so it prints: Math 10
10. Predict the output
Pricey fruit is anything over 20. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.