Overview
Curated: · Written: · Reviewed:
OOP & Data Classes
In one line
Python resolves methods, descriptors and special methods through the type, using a C3 MRO for multiple inheritance. Reach for @dataclass when a class is mostly fields and equality comes from those fields; write a plain class when identity or custom behaviour dominates.
Key definitions
- Bound method: a function found on the type, wrapped by its
__get__with the instance asself. - MRO: the C3 linearization of a class;
super()continues alongtype(self).__mro__, not to a named parent. - Descriptor: an object defining
__get__(and__set__for data descriptors) on a class. Methods andpropertyare descriptors. - Special method: a dunder such as
__len__or__eq__looked up ontype(obj), so instance attributes do not affectlen(),==orhash(). - InitVar / ClassVar: an init-only parameter passed to
__post_init__, and a class-level name excluded from fields. - Protocol vs ABC: a structural static shape versus a nominal contract with
register()and abstract methods.
How it works
obj.mfindsmontype(obj)through the MRO, calls its__get__, and returns a bound method holdingobj.- Attribute reads check data descriptors on the type, then the instance
__dict__, then class attributes and non-data descriptors. @dataclasswrites__init__,__repr__and__eq__into the class at creation time. A method you define yourself suppresses the generated one.- In a diamond,
D().close()walksD, B, C, A, object.Bdoes not shadowCbecause C3 keeps local order and placesAlast.
When to use and when not to
| Situation | Use | Avoid |
|---|---|---|
| Mostly data, equality from fields | @dataclass | Hand-written value class with drifting __eq__ |
| Hashable key | frozen=True with immutable fields | unsafe_hash=True on mutable state |
| Many stable instances | slots=True, after measuring | Subclasses that re-add __dict__ |
| Shared behaviour, unrelated types | Protocol | ABC inheritance forced on third-party types |
| Runtime nominal check, shared code | ABC | Protocol, when isinstance must mean subclass |
| Reuse without substitutability | Composition | Inheritance that exposes base internals |
Traps interviewers probe
- Shared class-level mutables.
items = []in the class body makes one list shared by every instance, anda.items.appendmutates it. Fix: create the list in__init__or usefield(default_factory=list). - Hard-coded class in a classmethod.
return Query(...)insidecountignores subclasses. Fix:return cls(...). - Hashing mutable state. Defining
__eq__sets__hash__toNone. Forcing a hash withunsafe_hash=Trueand then mutating a field makes the dict lookup miss, givingKeyError. Fix: frozen dataclass with identity fields. - Patching dunders on an instance.
w.__len__ = ...changesw.__len__()but notlen(w), because implicit lookup uses the type. Fix: define the protocol method on the class. - Overclaiming frozen.
frozen=Trueblocks attribute assignment only.cfg.tags += [...]mutates the list in place beforeFrozenInstanceErroris raised. Fix: tuple or frozenset fields.
Interview tips
Opening line: "Special methods and descriptors resolve on the type, so the class decides behaviour and the instance only holds state. A dataclass is code generation on top of that."
Expected follow-ups:
- Why
D().close()returns the method fromCin a diamond, and how cooperativesuper()chains must accept**kw. - Why defining
__eq__removes hashing, and what a frozen dataclass hashes. - What
__slots__saves, and why a subclass without slots gives the memory back. - Protocol vs ABC for a library extension point, and why
register()adds no methods. - Why
replace()reruns__post_init__, and why reordering fields breakscase Point(a, b). __init_subclass__and__set_name__before reaching for a metaclass.
30-second outline:
- Definition: the class holds state, the type owns behaviour, and
@dataclassgenerates the boilerplate. - Mechanism: name the lookup or MRO rule and show one example, such as
D, B, C, A, object. - Trade-off and fix: name the trap (shared mutable, unsafe hash, slots compatibility) and the change that avoids it.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.