Dataclasses & ABCs — Series 2

Preview — 3 of 10 questions

What is the output of the following code?

javascript
from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: int
    y: int

p = Point(1, 2)
print(p.x)
p.x = 10
A1, then the assignment silently does nothing — frozen=True only affects the generated __init__.
B1, then dataclasses.FrozenInstanceError: cannot assign to field 'x'
C1, then AttributeError: can't set attribute
DTypeError: Point() takes no arguments — frozen=True also removes the generated __init__.

What is the output of the following code?

javascript
from dataclasses import dataclass, field

@dataclass
class User:
    username: str
    password: str = field(repr=False)

u = User("ada", "secret123")
print(u)
AUser(username='ada', password='secret123')
BUser(username='ada', password=None)
CTypeError: field() got an unexpected keyword argument 'repr'
DUser(username='ada')

What is the output of the following code?

javascript
from dataclasses import dataclass, field

@dataclass
class Rectangle:
    width: float
    height: float
    area: float = field(init=False)

    def __post_init__(self):
        self.area = self.width * self.height

r = Rectangle(3, 4)
print(r.area)
A12
B0 — area is never actually computed, since field(init=False) also skips __post_init__.
CAttributeError: 'Rectangle' object has no attribute 'area'
DTypeError: __init__() got an unexpected keyword argument 'area'

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.