OOP in Python
This chapter treats objects as explicit state-and-behavior contracts, then develops inheritance, protocol-based polymorphism, data classes, special methods, and abstract interfaces without hiding Python's dynamic object model.
- Explain Classes & objects by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Inheritance & polymorphism by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Dunder methods by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Dataclasses by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Abstract Base Classes by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For OOP in Python, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the language learning arc appropriate to this subject.
The problem this chapter solves
This chapter treats objects as explicit state-and-behavior contracts, then develops inheritance, protocol-based polymorphism, data classes, special methods, and abstract interfaces without hiding Python's dynamic object model.
The language lets a team express business rules quickly while retaining escape hatches for typing, concurrency, native extensions, packaging, and performance profiling.
Learning outcomes
- Explain Classes & objects by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Inheritance & polymorphism by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Dunder methods by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Dataclasses by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Abstract Base Classes by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
CPython compiles a module to bytecode, executes frames on a virtual machine, stores ordinary objects on a managed heap, and primarily reclaims them through reference counting with a cyclic garbage collector as a backstop. Names point to objects; assignment does not copy an object. The Global Interpreter Lock protects interpreter state in the standard CPython build, so threads are excellent for much I/O but not a general CPU-parallelism mechanism. In OOP in Python, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- Python executes the module top to bottom, creating imported names, constants, classes, and function objects before the example call runs.
- The call creates a frame, binds arguments to local names, and validates or normalizes each boundary value before deriving the result.
- Expressions evaluate left to right subject to Python's short-circuit rules; container operations allocate objects and retain references described in the memory section.
- A deliberate exception immediately begins stack unwinding; otherwise
returnpasses the result reference to the caller and the frame becomes collectible when no suspended work retains it. - The final print or assertion exposes the observable value, and edge-case tests repeat the same trace with empty, invalid, duplicate, or worst-shape input.
Memory and performance lens
A local name lives in a frame's fast-locals storage, while the referenced object normally lives on the heap. Immutable objects may be shared or interned. Containers store references, not embedded copies. Generators and coroutines preserve suspended frames, so retained locals stay alive until completion or close(). For OOP in Python, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning OOP in Python, measure allocation count, retained-object size, iterator materialization, CPU profile, file/network call count, and execution time on representative input rather than optimizing from source-code appearance.
1. Classes & objects
The Classes & objects unit begins with __init__ and self: Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Classes & objects
| Concept | Meaning | Engineering decision |
|---|---|---|
| __init__ and self | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| instance vs class vs static attributes | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| @classmethod and @staticmethod | A class method receives the dynamic class and is useful for alternate construction or class-wide policy; a static method receives no implicit instance or class and is only namespaced by the class. | Use class methods for polymorphic factories and static methods only when the operation belongs conceptually beside the type but needs no object state. |
| __repr__ vs __str__ | __repr__ provides an unambiguous developer-facing representation; __str__ provides a readable user-facing representation and falls back to repr when absent. | Make repr identify the type and important fields while redacting secrets; keep str concise and domain-friendly. |
What the runtime actually does: Classes & objects
__init__ and self. Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
instance vs class vs static attributes. Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
@classmethod and @staticmethod. Descriptor binding turns a classmethod into a callable with cls bound and leaves a staticmethod function unbound. Subclasses therefore inherit a classmethod constructor that can create the subclass.
__repr__ vs __str__. repr(obj), interactive displays, and container representations call __repr__; str(obj) and default print formatting call __str__.
Read these as one system: __init__ and self establishes the starting contract, instance vs class vs static attributes changes how that contract is executed or represented, and __repr__ vs __str__ exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Classes & objects
1@classmethod2def from_text(cls, raw: str): return cls(raw.strip())This Classes & objects slice makes __init__ and self observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward __repr__ vs __str__, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Classes & objects
| Risk | Why it matters |
|---|---|
| __init__ and self | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
| instance vs class vs static attributes | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
| @classmethod and @staticmethod | Using staticmethod for behavior that needs replaceable dependencies often makes testing and subclassing harder than a module function or injected collaborator. |
| __repr__ vs __str__ | Including tokens, passwords, or personal data in either representation leaks them into logs and tracebacks. |
Code it, observe it, explain it: Classes & objects
- Foundation: implement or demonstrate __init__ and self with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine __init__ and self with instance vs class vs static attributes. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for __repr__ vs __str__. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Inheritance & polymorphism
The Inheritance & polymorphism unit begins with single and multiple inheritance: Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Inheritance & polymorphism
| Concept | Meaning | Engineering decision |
|---|---|---|
| single and multiple inheritance | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| MRO (Method Resolution Order) | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| super() usage | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| method overriding | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| duck typing | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
What the runtime actually does: Inheritance & polymorphism
single and multiple inheritance. Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
MRO (Method Resolution Order). Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
super() usage. Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
method overriding. Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
duck typing. Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
Read these as one system: single and multiple inheritance establishes the starting contract, MRO (Method Resolution Order) changes how that contract is executed or represented, and duck typing exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Mistakes that change program meaning: Inheritance & polymorphism
| Risk | Why it matters |
|---|---|
| single and multiple inheritance | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
| MRO (Method Resolution Order) | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
| super() usage | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
| method overriding | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
| duck typing | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
Code it, observe it, explain it: Inheritance & polymorphism
- Foundation: implement or demonstrate single and multiple inheritance with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine single and multiple inheritance with MRO (Method Resolution Order). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for duck typing. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Dunder methods
The Dunder methods unit begins with __len__/__getitem__/__setitem__: Container dunder methods let an object participate in built-in length, indexing, slicing, iteration fallback, and assignment syntax. Implement the smallest coherent container protocol and raise the conventional IndexError, KeyError, or TypeError. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Dunder methods
| Concept | Meaning | Engineering decision |
|---|---|---|
| __len__/__getitem__/__setitem__ | Container dunder methods let an object participate in built-in length, indexing, slicing, iteration fallback, and assignment syntax. | Implement the smallest coherent container protocol and raise the conventional IndexError, KeyError, or TypeError. |
| __eq__/__lt__/__gt__ for comparison | Rich comparison methods define value equality and ordering operations and may return NotImplemented for unsupported peer types. | Compare the fields that define domain identity and use functools.total_ordering only when its convenience outweighs slower derived methods. |
| __enter__/__exit__ for context managers | A context manager brackets a block with deterministic setup and cleanup. | Use it for files, transactions, locks, temporary settings, and spans. |
| __call__ and __slots__ | __call__ makes an instance callable; __slots__ declares a restricted instance layout that can reduce per-object overhead and prevent arbitrary attributes. | Use callable objects for configured strategies with inspectable state and slots only after memory profiling or to enforce a closed attribute set. |
What the runtime actually does: Dunder methods
__len__/__getitem__/__setitem__. len requires a non-negative integer from __len__; subscription passes an integer, slice, or other key to __getitem__; assignment dispatches to __setitem__.
__eq__/__lt__/__gt__ for comparison. Python tries the reflected comparison where appropriate after NotImplemented; hashing must remain consistent with equality for dictionary/set keys.
__enter__/__exit__ for context managers. The with statement calls __enter__, runs the body, then calls __exit__ even during stack unwinding. __exit__ can suppress an exception only by returning truthy.
__call__ and __slots__. Calling the instance dispatches to its class's __call__. Slotted fields use descriptors rather than a normal per-instance __dict__ unless one is explicitly included.
Read these as one system: __len__/__getitem__/__setitem__ establishes the starting contract, __eq__/__lt__/__gt__ for comparison changes how that contract is executed or represented, and __call__ and __slots__ exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Mistakes that change program meaning: Dunder methods
| Risk | Why it matters |
|---|---|
| __len__/__getitem__/__setitem__ | Surprising side effects or inconsistent negative-index/slice behavior violates users' expectations of a Python container. |
| __eq__/__lt__/__gt__ for comparison | Overriding equality on a mutable object and keeping object hashing can corrupt set/dictionary expectations. |
| __enter__/__exit__ for context managers | Do not hide unexpected exceptions in __exit__; cleanup should be exception-safe. |
| __call__ and __slots__ | Slots complicate multiple inheritance, weak references, serialization, and migrations; they are not a universal speed switch. |
Code it, observe it, explain it: Dunder methods
- Foundation: implement or demonstrate __len__/__getitem__/__setitem__ with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine __len__/__getitem__/__setitem__ with __eq__/__lt__/__gt__ for comparison. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for __call__ and __slots__. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. Dataclasses
The Dataclasses unit begins with @dataclass decorator: A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Dataclasses
| Concept | Meaning | Engineering decision |
|---|---|---|
| @dataclass decorator | A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
| field() with validators | A data class generates repetitive value-object methods from annotated fields. | Use it for explicit records and domain values with validation in __post_init__. |
| frozen=True for immutability | A data class generates repetitive value-object methods from annotated fields. | Use it for explicit records and domain values with validation in __post_init__. |
| nested dataclasses | A data class generates repetitive value-object methods from annotated fields. | Use it for explicit records and domain values with validation in __post_init__. |
What the runtime actually does: Dataclasses
@dataclass decorator. Decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references. wraps preserves metadata and the wrapped chain.
field() with validators. The decorator rewrites the class by adding methods such as __init__, comparison, and representation according to options. frozen blocks normal assignment but is not deep immutability.
frozen=True for immutability. The decorator rewrites the class by adding methods such as __init__, comparison, and representation according to options. frozen blocks normal assignment but is not deep immutability.
nested dataclasses. The decorator rewrites the class by adding methods such as __init__, comparison, and representation according to options. frozen blocks normal assignment but is not deep immutability.
Read these as one system: @dataclass decorator establishes the starting contract, field() with validators changes how that contract is executed or represented, and nested dataclasses exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Dataclasses
1@dataclass(frozen=True, slots=True)2class Value:3 amount: DecimalThis Dataclasses slice makes @dataclass decorator observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward nested dataclasses, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Dataclasses
| Risk | Why it matters |
|---|---|
| @dataclass decorator | Keep retries bounded and restricted to transient, idempotent operations. |
| field() with validators | Use default_factory for mutable defaults and validate nested mutable state. |
| frozen=True for immutability | Use default_factory for mutable defaults and validate nested mutable state. |
| nested dataclasses | Use default_factory for mutable defaults and validate nested mutable state. |
Code it, observe it, explain it: Dataclasses
- Foundation: implement or demonstrate @dataclass decorator with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine @dataclass decorator with field() with validators. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for nested dataclasses. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. Abstract Base Classes
The Abstract Base Classes unit begins with abc module and ABC: Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Abstract Base Classes
| Concept | Meaning | Engineering decision |
|---|---|---|
| abc module and ABC | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| @abstractmethod | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| Protocol (structural subtyping, 3.8+) | Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
What the runtime actually does: Abstract Base Classes
abc module and ABC. Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
@abstractmethod. Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
Protocol (structural subtyping, 3.8+). Attribute lookup walks the instance, its class, and the class MRO. super() follows that computed MRO, enabling cooperative multiple inheritance when signatures agree.
Read these as one system: abc module and ABC establishes the starting contract, @abstractmethod changes how that contract is executed or represented, and Protocol (structural subtyping, 3.8+) exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Abstract Base Classes
1class Port(ABC):2 @abstractmethod3 def save(self, item): ...This Abstract Base Classes slice makes abc module and ABC observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward Protocol (structural subtyping, 3.8+), predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Abstract Base Classes
| Risk | Why it matters |
|---|---|
| abc module and ABC | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
| @abstractmethod | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
| Protocol (structural subtyping, 3.8+) | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. |
Code it, observe it, explain it: Abstract Base Classes
- Foundation: implement or demonstrate abc module and ABC with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine abc module and ABC with @abstractmethod. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for Protocol (structural subtyping, 3.8+). State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1from dataclasses import dataclass, field2from datetime import date, timedelta3from typing import Protocol4
5class FinePolicy(Protocol):6 def amount(self, due: date, returned: date) -> int: ...7
8@dataclass(frozen=True, slots=True)9class Book:10 isbn: str11 title: str12
13@dataclass(slots=True)14class Loan:15 book: Book16 issued_on: date17 due_on: date = field(init=False)18
19 def __post_init__(self) -> None:20 self.due_on = self.issued_on + timedelta(days=14)21
22 def __str__(self) -> str:23 return f"{self.book.title} due {self.due_on:%Y-%m-%d}"24
25print(Loan(Book("978-1", "Python Internals"), date(2026, 8, 28)))Expected result
1Python Internals due 2026-09-11Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | from dataclasses import dataclass, field | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 2 | from datetime import date, timedelta | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 3 | from typing import Protocol | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 5 | class FinePolicy(Protocol): | Creates a class namespace and binds the resulting class object to this name. |
| 6 | def amount(self, due: date, returned: date) -> int: ... | Defines a function; its parameters form the explicit input boundary. |
| 8 | @dataclass(frozen=True, slots=True) | Applies a decorator or framework annotation before the following definition is bound. |
| 9 | class Book: | Creates a class namespace and binds the resulting class object to this name. |
| 10 | isbn: str | Implements the next python statement in the example's data flow. |
| 11 | title: str | Implements the next python statement in the example's data flow. |
| 13 | @dataclass(slots=True) | Applies a decorator or framework annotation before the following definition is bound. |
| 14 | class Loan: | Creates a class namespace and binds the resulting class object to this name. |
| 15 | book: Book | Implements the next python statement in the example's data flow. |
| 16 | issued_on: date | Implements the next python statement in the example's data flow. |
| 17 | due_on: date = field(init=False) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 19 | def __post_init__(self) -> None: | Defines a function; its parameters form the explicit input boundary. |
| 20 | self.due_on = self.issued_on + timedelta(days=14) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 22 | def __str__(self) -> str: | Defines a function; its parameters form the explicit input boundary. |
| 23 | return f"{self.book.title} due {self.due_on:%Y-%m-%d}" | Returns the observable result to the caller and ends this invocation. |
| 25 | print(Loan(Book("978-1", "Python Internals"), date(2026, 8, 28))) | Emits the example's observable output. |
Step-by-step execution
- Python executes the module top to bottom, creating imported names, constants, classes, and function objects before the example call runs.
- The call creates a frame, binds arguments to local names, and validates or normalizes each boundary value before deriving the result.
- Expressions evaluate left to right subject to Python's short-circuit rules; container operations allocate objects and retain references described in the memory section.
- A deliberate exception immediately begins stack unwinding; otherwise
returnpasses the result reference to the caller and the frame becomes collectible when no suspended work retains it. - The final print or assertion exposes the observable value, and edge-case tests repeat the same trace with empty, invalid, duplicate, or worst-shape input.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Classes & objects | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| Inheritance & polymorphism | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
| Dunder methods | Surprising side effects or inconsistent negative-index/slice behavior violates users' expectations of a Python container. | Implement the smallest coherent container protocol and raise the conventional IndexError, KeyError, or TypeError. |
| Dataclasses | Keep retries bounded and restricted to transient, idempotent operations. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
| Abstract Base Classes | Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. | Prefer composition or small protocols; use inheritance for a genuine substitutable abstraction. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the Library Management System project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Classes & objects: __init__ and self
- To do: Classes & objects: instance vs class vs static attributes
- To do: Classes & objects: @classmethod and @staticmethod
- To do: Classes & objects: __repr__ vs __str__
- To do: Inheritance & polymorphism: single and multiple inheritance
- To do: Inheritance & polymorphism: MRO (Method Resolution Order)
- To do: Inheritance & polymorphism: super() usage
- To do: Inheritance & polymorphism: method overriding
- To do: Inheritance & polymorphism: duck typing
- To do: Dunder methods: __len__/__getitem__/__setitem__
- To do: Dunder methods: __eq__/__lt__/__gt__ for comparison
- To do: Dunder methods: __enter__/__exit__ for context managers
- To do: Dunder methods: __call__ and __slots__
- To do: Dataclasses: @dataclass decorator
- To do: Dataclasses: field() with validators
- To do: Dataclasses: frozen=True for immutability
- To do: Dataclasses: nested dataclasses
- To do: Abstract Base Classes: abc module and ABC
- To do: Abstract Base Classes: @abstractmethod
- To do: Abstract Base Classes: Protocol (structural subtyping, 3.8+)
Quick revision
- Classes & objects: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Inheritance & polymorphism: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Dunder methods: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Dataclasses: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Abstract Base Classes: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?