This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Dataclasses, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
Which decorator turns a class into a dataclass?
Answer: @dataclass
Why: The dataclass decorator reads the annotated fields and generates common methods.
What does a dataclass generate by default?
Answer: __init__, __repr__, and __eq__
Why: The default dataclass provides initialization, display, and value equality.
What does frozen=True prevent?
Answer: Attribute assignment
Why: A frozen dataclass raises an error when an attribute is assigned after creation.
What does the program output?
from dataclasses import dataclass
@dataclass
class P:
x: int
print(P(1))Answer: P(x=1)
Why: The generated repr includes the class name and field values.
Complete the module that provides dataclass.
from ____ import dataclassAnswer: dataclasses
Why: The decorator is imported from dataclasses.
Complete the field annotation.
from dataclasses import dataclass
@dataclass
class P:
x: ____Answer: int
Why: x is declared as an integer field.
Complete the default value for active.
from dataclasses import dataclass
@dataclass
class U:
name: str
active: bool = ____Answer: True
Why: active defaults to True when it is omitted.
Complete the function that converts the instance to a dictionary.
from dataclasses import dataclass, asdict
@dataclass
class P:
x: int
p = P(2)
print(____(p))Answer: asdict
Why: asdict returns a plain dictionary of field names and values.
What appears on the screen?
from dataclasses import dataclass
@dataclass
class P:
x: int
print(P(2))Answer: P(x=2)
Why: The generated repr shows the class and the field, P(x=2).
What is printed?
from dataclasses import dataclass
@dataclass
class P:
x: int
print(P(1) == P(1))Answer: True
Why: Dataclasses compare their fields, so two instances with x=1 are equal.
What is the output?
from dataclasses import dataclass
@dataclass
class U:
name: str
active: bool = True
print(U("Ada").active)Answer: True
Why: The default active value is True, and the instance exposes it.
What does this code print?
from dataclasses import dataclass, asdict
@dataclass
class P:
x: int
print(asdict(P(2)))Answer: {'x': 2}
Why: asdict returns a plain dictionary with the field value.
Try the questions first
Open the practice page for Python Dataclasses and answer the same 12 questions with instant feedback.