Editor

Predict Frozen Behavior

Intermediate · Predict the output · from Python Dataclasses: Less Boilerplate, More Readable Code

From the lesson: Python Dataclasses: Less Boilerplate, More Readable Code

Imagine filling out a form where you have to write your name, address, and phone number. Now imagine filling out 50 forms where every single one asks for the same information in a slightly different format. That's what writing Python classes feels like sometimes.

Read the lesson

What does this code print? Think about what frozen=True does.

from dataclasses import dataclass

@dataclass(frozen=True)
class City:
    name: str
    population: int

c = City('Tokyo', 14000000)
print(c.name)
try:
    c.population = 0
except AttributeError:
    print('Cannot modify frozen dataclass')
# What does this code print?
print('Tokyo')
print('Cannot modify frozen dataclass')

More Dataclass exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz