Predict the Output: Frozen Dataclass
Intermediate · Predict the output · from Advanced Dataclasses: __post_init__, frozen, field(), slots, and Inheritance
From the lesson: Advanced Dataclasses: __post_init__, frozen, field(), slots, and Inheritance
You already know the basics of dataclasses - how to define fields, get automatic __init__ and __repr__, and set default values. Now it's time to unlock the advanced features.
Read the lessonRead the code carefully. What will be printed? Think about what happens when you try to modify a frozen dataclass and whether two identical frozen instances are equal.
from dataclasses import dataclass
@dataclass(frozen=True)
class Coin:
value: int
name: str
c1 = Coin(25, 'Quarter')
c2 = Coin(25, 'Quarter')
print(c1 == c2)
print(c1.name)
try:
c1.value = 50
print('Changed!')
except Exception:
print('Frozen!')
More Advanced Dataclass exercises
- Validate with __post_init__Beginner
- Safe List Default with field()Beginner
- Computed Field with __post_init__Intermediate
- Dataclass InheritanceAdvanced
- Refactor: Add Validation and Computed FieldsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz