Skip to content
Tech Interview Prep
Technical interview guide

OOP & Data Classes

Classes, inheritance, and the @dataclass shortcut for the common case of a class that's mostly just data.

Read
50 min
Practice MCQs
25
Interview Q&A
25
Edition
v2
Editorial status
Reviewed

Scope: Python 3.14 object model, dataclasses, typing.Protocol, and abstract base classes.

Curated: · Written: · Reviewed:

25 questions

MCQ-1A checkout service keeps a cart's `add` method in a variable, then reuses the name `c` for a second cart: ```python class Cart: def __init__(self, name): self.name = name self.count = 0 def add(self, item): self.count += 1 return f"{self.name}:{self.count}" c = Cart('A') f = c.add c = Cart('B') print(f('x'), c.add('y')) ``` What does this print?
MCQ-3A Python 3.12 module defines: ```python class Cart: items = [] def add(self, sku): self.items.append(sku) ``` A test runs: ```python a = Cart() b = Cart() a.add("A1") b.items = ["B2"] b.add("B3") print(a.items, b.items, Cart.items) ``` What does it print?
MCQ-2A query builder defines two classmethod alternate constructors on `Query`; `CachedQuery` subclasses it and adds a `ttl` field with a default: ```python class Query: def __init__(self, sql, params=()): self.sql = sql self.params = params @classmethod def select(cls, table): return Query(f"SELECT * FROM {table}") @classmethod def count(cls, table): return cls(f"SELECT COUNT(*) FROM {table}") class CachedQuery(Query): def __init__(self, sql, params=(), ttl=60): super().__init__(sql, params) self.ttl = ttl ``` In a REPL, `type(CachedQuery.count("users")).__name__` prints `'CachedQuery'`, `type(CachedQuery.select("users")).__name__` prints `'Query'`, and `CachedQuery("SELECT 1").ttl` prints `60`. Which statement explains the difference?
MCQ-8A `Batch` class defines `__len__` returning `len(self.items)`. A test runs `b = Batch([1, 2, 3])`, then `b.__len__ = lambda: 99`, and asserts `len(b) == 99`. The assertion fails: `len(b)` is still 3, even though `b.__len__()` returns 99. Which statement explains the failure?
MCQ-4A code review hits this hierarchy before it ships: ```python class A: def close(self): return "A" class B(A): pass class C(A): def close(self): return "C" class D(B, C): pass ``` What does `D().close()` return, and what decides it?
MCQ-5A codebase defines these classes: ```python class Root: def ping(self): return 'Root' class Left(Root): def ping(self): return 'Left>' + Root.ping(self) class Right(Root): def ping(self): return 'Right>' + super().ping() class Both(Left, Right): def ping(self): return 'Both>' + super().ping() ``` What does `Both().ping()` return?
MCQ-6Python 3.11. The module below runs in CPython. What does it print, and why? ```python events = [] class Base: def __init__(self): events.append('Base') super().__init__() class Logging(Base): def __init__(self): super().__init__() events.append('Logging') class Metrics(Base): def __init__(self): super().__init__() events.append('Metrics') class Service(Logging, Metrics): def __init__(self): Logging.__init__(self) Metrics.__init__(self) Service() print(events) ```
MCQ-9Two classes model temperatures: ```python class Temp: def __init__(self, c): self.c = c def __eq__(self, other): if isinstance(other, Temp): return self.c == other.c return False class Fahrenheit: def __init__(self, f): self.f = f def __eq__(self, other): if isinstance(other, Fahrenheit): return self.f == other.f if isinstance(other, Temp): return self.f == other.c * 9 / 5 + 32 return NotImplemented ``` What do `Temp(20) == Fahrenheit(68)` and `Fahrenheit(68) == Temp(20)` return?
MCQ-10A `Money` class with mutable `amount` and `currency` attributes defines `__eq__` comparing both fields. After that change, adding an instance to a `set` raises `TypeError: unhashable type: 'Money'`. Which statement explains why the class became unhashable and why hashing the mutable fields would be unsafe?
MCQ-11A team defines `@dataclass class Span: name: str; duration_ms: int; tags: list = field(default_factory=list)` and later `{Span("db", 3)}` raises `TypeError: unhashable type: 'Span'`. Which statement describes what the decorator generated for this class?
MCQ-17A service caches per-session payloads in a dict keyed by a dataclass (Python 3.11): ```python from dataclasses import dataclass @dataclass(unsafe_hash=True) class Session: user_id: int token: str s = Session(7, "abc") cache = {s: "payload"} s.user_id = 8 print(s in cache, cache.get(s), len(cache)) ``` What does this print, and why?
MCQ-18A team writes `@dataclass class Reading: sensor: str; value: float`, then constructs `Reading(sensor=7, value="high")` and expects a `TypeError`. The constructor accepts both arguments and raises nothing. Which statement explains why?
MCQ-13A service defines the dataclass below. A test constructs one `Cart` and appends `"apple"` to `items`. What does the test observe? ```python from dataclasses import dataclass, field @dataclass class Cart: items: list = field(default_factory=list()) ```
MCQ-16A service stores parsed config in a frozen dataclass and hands the same instance to several handlers: ```python @dataclass(frozen=True) class Cfg: name: str tags: list[str] cfg = Cfg("api", ["base"]) other = cfg try: cfg.tags += ["debug"] err = "none" except Exception as e: err = type(e).__name__ print(err, other.tags) ``` What does this print?
MCQ-15A dataclass caps a batch at a class-level limit and takes an initialization-only shrink amount: ```python from dataclasses import dataclass, field, InitVar, ClassVar @dataclass class Batch: LIMIT: ClassVar[int] = 100 batch_id: str rows: int shrink: InitVar[int] = 0 effective: int = field(init=False) def __post_init__(self, shrink): self.effective = min(self.rows, self.LIMIT) - shrink ``` With `a = Batch("B1", 250, 40)`, which statement about `a` is true?
MCQ-14A service derives a display label in `__post_init__`. A subclass adds a custom `__init__` to carry an extra `timeout` argument: ```python from dataclasses import dataclass, field, InitVar @dataclass class Job: name: str retries: InitVar[int] = 3 label: str = field(init=False) def __post_init__(self, retries): self.label = f"{self.name}-r{retries}" @dataclass class TimedJob(Job): def __init__(self, name, retries, timeout): self.name = name self.timeout = timeout j = TimedJob("sync", 5, 30) print(j.label) ``` What does the final `print` output?
MCQ-20A base dataclass declares `name: str = "base"`. A derived dataclass adds `count: int` with no default and no `kw_only`. What happens when the derived class is defined?
MCQ-24A shared library declares `@dataclass class Point: x: float; y: float; z: float = 0.0`. A downstream service matches points with `case Point(a, b):` and computes `a - b`. A refactor reorders the fields to `y, x, z`; the library's own tests still pass, but the service silently starts returning negated distances. What caused the silent break?
MCQ-23A worker retries a job by rebuilding it with `dataclasses.replace`, and every job registers itself in a module-level audit list from `__post_init__`: ```python import dataclasses, itertools _ids = itertools.count(1) AUDIT = [] @dataclasses.dataclass class Job: name: str attempts: int = 0 id: int = dataclasses.field(init=False) def __post_init__(self): self.id = next(_ids) AUDIT.append(self) job = Job("resize") for _ in range(3): job = dataclasses.replace(job, attempts=job.attempts + 1) ``` After the loop, what does `AUDIT` contain?
MCQ-25A codebase has `Job`, a plain (non-frozen) `@dataclass` with fields `id` and `priority`. A teammate writes `@dataclass(frozen=True) class RetryJob(Job): attempt: int = 0` to add an immutable variant. What does the dataclass decorator do when `RetryJob` is defined?
MCQ-12A telemetry service keeps roughly four million small `Sample` objects, each with two float fields, and profiling shows most of the heap is per-instance `__dict__` overhead. The team adds `__slots__ = ("x", "y")` to the plain `Sample` class. Which statement describes what that change does?
MCQ-19A service keeps 2 million `Reading` objects alive. `Reading` is vendored and defines no `__slots__`: ```python class Reading: def __init__(self, t, v, q): self.t, self.v, self.q = t, v, q ``` A prototype that added `__slots__ = ('t', 'v', 'q')` to `Reading` cut resident memory by about 300 MB. Unable to edit the vendored class, the team instead subclasses it and switches the pipeline over: ```python class Calibrated(Reading): __slots__ = ('offset',) def __init__(self, t, v, q, offset): super().__init__(t, v, q) self.offset = offset ``` Resident memory is unchanged from before the change. What accounts for the missing saving?
MCQ-21On CPython 3.12, `@dataclass(slots=True)` is applied to `Config`, which inherits only from `object` and declares `host: str` and `port: int`. Instances register and stay retrievable in a `WeakValueDictionary`, but a serializer that calls `vars(cfg)` now raises `TypeError: vars() argument must have __dict__ attribute`. What explains this?
MCQ-22A teammate calls `Shape.register(ThirdPartyPolygon)` so that `isinstance(ThirdPartyPolygon(), Shape)` returns True, then expects `ThirdPartyPolygon` to inherit `Shape`'s concrete `describe()` method and to list `Shape` in its `__mro__`. Which statement describes what `register()` actually does?
MCQ-7A payments service defines `PaymentMethod` with `charge(cents)` and `refund(receipt)`. `GiftCard` was added by subclassing `PaymentMethod`, but gift cards cannot be refunded, so its `refund` throws `UnsupportedOperation`. The nightly refund worker iterates `List<PaymentMethod>` and calls `refund` on each item; each failure is retried 5 times, and the dead-letter queue now takes about 40,000 messages a night, one per attempt. Two more non-refundable methods, prepaid cards and vouchers, ship next quarter. Which redesign fits?