Embercode
✕
Object-Oriented ProgrammingQuick quiz

Immutable and equality

8 questions. Covers Operator overloading with __eq__, __hash__, __lt__ and __str__.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``python from dataclasses import dataclass, replace @dataclass(frozen=True) class Point: x: int y: int p = Point(3, 4) moved = replace(p, x=p.x + 10) print(p, moved) ``
  2. 2. A dataclass Range checks in __post_init__ that low is not above high. What does Range(9, 2) do? ``python @dataclass(frozen=True) class Range: low: int high: int def __post_init__(self): if self.low > self.high: raise ValueError(f"low {self.low} is above high {self.high}") ``
  3. 3. The output shows a change to an object that was meant to be fixed. What is the bug? ``python from dataclasses import dataclass @dataclass(frozen=True) class Team: name: str members: list names = ["Asha"] team = Team("Blue", names) names.append("Ravi") print(team) ` Output: Team(name='Blue', members=['Asha', 'Ravi'])`
  4. 4. True or false: for @dataclass class Point: x: int, the way to read the value is p.get_x(), because dataclasses write a getter for every field.
  5. 5. What does this program print? ``python class Money: def __init__(self, cents): self._cents = cents def __eq__(self, other): if not isinstance(other, Money): return NotImplemented return self._cents == other._cents def __hash__(self): return hash(self._cents) a = Money(1050) b = Money(1050) print(a == b, a is b, a == "$10.50") ``

5 question(s) left on this page.