Composition, inheritance and super
Reuse behaviour without building an accidental hierarchy.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners who can read small Python functions and want to apply the listed foundations.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain model a real substitutable relationship
- Apply delegate responsibilities
- Reason about control extension points
Model a real substitutable relationship
Inheritance says that a child object can be used where its parent is expected. Shared spelling is not enough; the child must keep the parent's promises.
Understand first
A caller that knows Sender should be able to use TaggedSender without special cases. Inherit to extend a meaningful role. Do not inherit merely because another class contains a useful helper.
Words you will see
- Base / subclass
- A parent type and a child type that inherits its behavior.
- Override
- A subclass method replacing inherited behavior for that method name.
- Substitution
- Using a child object through the parent's documented interface.
Keep the promise while changing the detail
Sender.send accepts a message string and returns a string beginning sent:. TaggedSender overrides send to prefix the message, then delegates to the next implementation using super(). A caller still supplies one string and receives one string.
isinstance is True because TaggedSender inherits from Sender. That structural fact does not prove a correct behavioral relationship: an override could still discard the message, return None or raise for all ordinary inputs.
Choose has-a instead of is-a when appropriate
A report is not a formatter even if it uses formatting. Give a report a formatter field instead. Composition makes replacement explicit and avoids inheriting methods that the report cannot meaningfully support.
Avoid subclasses that disable normal parent operations. If a parent promises mutable collection operations, a child that rejects all mutations is not a safe replacement under that promise. Document the small API callers actually need rather than relying on a family resemblance.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
class TaggedSender(Sender):Declare the child relationship.
return super().send("[study] " + message)Add a tag while keeping the parent result convention.
sender = TaggedSender()Create a child instance.
print(isinstance(sender, Sender))Check ancestry, not behavioral correctness.
Inheritance is useful when an implementation genuinely satisfies the parent's contract. If a subclass must disable expected operations, the relationship may be wrong. Composition makes a dependency explicit and allows independent testing or replacement.
Conceptual substitution boundary, not a call trace from edited code
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Caller promisesend(message: string) must return a string with the sent: prefix.
- Child adaptationTaggedSender adds a tag but forwards an ordinary string to the next send implementation.
- Observable resultThe result remains a string, so the caller does not need a child-specific branch.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Send an empty message.
Try: Replace "ready" with "" in the call.
The returned string is sent:[study] ; the role still works for the empty string.
Break the return contract visibly.
Try: Remove return from the override's super call.
The first print becomes None even though the ancestry check remains True.
Before you move on
If TaggedSender.send prints the message but returns None, is it still a good Sender here?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. It may still pass isinstance, but callers expect a returned string. Printing is a side effect, not a replacement for the promised result.
Delegate responsibilities
Delegation means passing a responsibility to a collaborator. Constructor injection makes that collaborator a visible input instead of a hidden global dependency.
Understand first
You may need plain output today and bracketed output tomorrow. Changing the collaborator avoids copying the summing logic or creating one summary subclass for every display style.
Words you will see
- Collaborator
- An object that supplies one responsibility to another object.
- Injection
- Passing a dependency explicitly, often in __init__.
- Duck typing
- Using supported operations without requiring a particular ancestry.
Separate two decisions
Summary owns summing values. Plain and Bracketed each own formatting a total. Summary stores the supplied formatter and calls its format method. Both formatters work because both implement the needed method; no common base class is required.
The stored formatter is a shared reference, not a clone. If it is stateful, its lifetime and mutations matter. This example's formatters have no mutable state, so sharing them has no observable write effect.
Make replacement and failure explicit
For [2, 3], sum produces five. Plain converts five to "5"; Bracketed surrounds it with brackets. The source list is only read. For an empty list sum supplies zero, so the same collaborators can render "0" or "[0]".
An object without format fails with AttributeError at the call. Do not catch that and invent a default result. Define the required collaborator interface and test it. Summing n numbers takes linear work; formatting cost depends on the collaborator. No source-list copy is needed because no mutation occurs.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
self.formatter = formatterKeep the explicitly supplied collaborator.
return self.formatter.format(sum(values))Calculate a total, then delegate text construction.
print(Summary(Plain()).render(values))The same total becomes plain text.
print(Summary(Bracketed()).render(values))A different collaborator changes only the presentation.
A report service can receive a formatter rather than inherit from one. The service owns orchestration; the formatter owns representation. Keep constructor inputs explicit so callers can supply a test implementation without global patching.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Change only display style.
Try: Change Bracketed.format to return f"<{total}>".
Only the second result becomes <5>; the aggregation stays the same.
Check a repeated value.
Try: Set values = [2, 2, 3].
Both summaries use total seven; repeated entries are not removed.
Before you move on
Must Bracketed inherit from Plain for Summary to use it?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Summary only needs a callable format(total) with the documented result. A shared base may document the interface, but ancestry is not needed for this delegation.
Compose a formatter
A composed report coordinates collaborators: it computes the total and asks a formatter for the representation.
Understand first
This original example brings aggregation and formatting together without a hierarchy. It requires method calls, sum and constructor state, not a framework or a browser network service.
Words you will see
- Orchestration
- Choosing the sequence of tasks while delegating the details.
- Interface
- The operations and results a collaborator must provide.
- Dependency
- An object the report needs to do its work.
Read the original program in order
Formatter.format creates the string Total: followed by a numeric total. Report.__init__ receives and stores a formatter. Report.render sums the supplied values before calling that object's format method.
Report(Formatter()) first makes a Formatter instance, then passes it into Report construction. render([2, 3]) calculates five. Only the final print displays the returned text; render does not print by itself.
A small contract beats a large family tree
A replacement formatter could return a different string while the report stays unchanged. A test formatter can record the total it receives, proving that render passes five, not the original list. The report does not own or modify that input list.
A generator of numbers also works with sum, but would be consumed. Reading a list does not consume it; reading an iterator can. State supported input types in a public contract. Here summing n numbers is linear in n and uses constant running aggregation space, excluding the input and formatter's own work.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
return f'Total: {total}'Create representation after receiving a numeric total.
self.formatter = formatterRetain the collaborator, not a parent relationship.
return self.formatter.format(sum(values))Sum first, then delegate.
print(Report(Formatter()).render([2, 3]))Construct both objects and print Total: 5.
The report depends on a formatter contract; replacing formatting does not require changing the aggregation.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Use an empty report.
Try: Change [2, 3] to [].
It prints Total: 0 because the empty sum is zero.
Change presentation without aggregation.
Try: Change the f-string prefix to Counted total:.
The prefix changes but the number remains five.
Before you move on
If the list is [2, 3, 3], what argument reaches Formatter.format?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The integer 8. Report aggregates all three entries before calling format; it does not remove duplicates or pass the list itself.
Where this idea earns its place
Inheritance declares a substitutability relationship, not merely that two classes have some common code. A subclass should satisfy the expectations of callers written for its base. Composition instead supplies another object to perform a responsibility, making replacement and independent tests possible without expanding a type hierarchy.
Follow the mechanism step by step
Method lookup follows the class's method resolution order. super continues through that order rather than simply naming one textual parent. Cooperative multiple inheritance needs methods that agree on compatible parameters and consistently delegate, otherwise one class can be skipped or receive unexpected arguments.
Work through a concrete application
Build a report service that accepts a formatter and a repository. Test it with small fake collaborators, then separately test the real adapters. If a requirement changes formatting, replace the formatter without changing aggregation. Reserve subclassing for a real public contract where callers should be able to use any implementation interchangeably.
Failure cases and misleading shortcuts
A subclass that raises errors for operations the base promises to support often signals a bad relationship. Directly invoking a chosen base method can bypass cooperative resolution. Inheritance also couples the subclass to undocumented base behaviour, making upgrades risky when tests assert only a few happy-path outputs.
Cost, ownership and alternatives
Composition introduces explicit collaborator objects but usually reduces the number of hidden dependencies. Multiple inheritance can be powerful for carefully designed mixins, yet its reasoning cost grows with interacting state and lifecycle rules. Evaluate the maintenance and testing cost, not just code reuse.
Verify the contract
Write contract tests against the behaviour shared by implementations. Include failure and ownership semantics, not only matching method names. For a hierarchy, inspect and test the MRO where order matters; for composition, verify integration between real collaborators as well as tests using fakes.
Transfer question: A read-only storage object cannot implement every mutating method of a base storage class. What would you reconsider?
Separate read and write capabilities into smaller contracts and let consumers depend only on what they need. A read-only adapter can then satisfy the reading interface without pretending to support writes. Composition or structural protocols may fit better than forcing a misleading subtype.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Compose a formatter
Without copying the worked code, reproduce its observable contract: The report depends on a formatter contract; replacing formatting does not require changing the aggregation. Then change one boundary input and explain the result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Delegate report formatting
Compute one total and pass it to the supplied formatter's format method. Return its text without changing the caller's values.
The contract
- values is a list of integers, including repeats, negatives or an empty list.
- formatter.format(total) returns a string. Call it exactly once with the integer sum, including zero for empty input.
- Return that exact string value. Do not mutate values or replace the supplied formatter; its intentional call-recording state may change.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Delegate numeric total
from types import SimpleNamespace seen = [] f = SimpleNamespace(format=lambda total: (seen.append(total), f"total={total}")[1]) r = render_report([2, 3], f) assert type(r) is str and r == "total=5" and seen == [5] and type(seen[0]) is int - Empty total still formats
from types import SimpleNamespace seen = [] f = SimpleNamespace(format=lambda n: (seen.append(n), f"[{n}]")[1]) r = render_report([], f) assert type(r) is str and r == "[0]" and seen == [0] and type(seen[0]) is int - Duplicates count
from types import SimpleNamespace seen = [] f = SimpleNamespace(format=lambda n: (seen.append(n), str(n))[1]) r = render_report([3, 3, 1], f) assert type(r) is str and r == "7" and seen == [7]
- Negatives and cancellation
from types import SimpleNamespace seen = [] f = SimpleNamespace(format=lambda n: (seen.append(n), str(n))[1]) r = render_report([-4, 4], f) assert type(r) is str and r == "0" and seen == [0]
- Input ownership and returned text
from types import SimpleNamespace values = [4, 1, 4] seen = [] f = SimpleNamespace(format=lambda n: (seen.append(n), f"<{n}>")[1]) r = render_report(values, f) assert type(r) is str and r == "<9>" and seen == [9] and values == [4, 1, 4] - Collaborator errors visible
class Broken: def __init__(self): self.calls = [] def format(self, n): self.calls.append(n) raise ValueError("format failed") f = Broken() values = [2] try: render_report(values, f) except ValueError as error: assert str(error) == "format failed" else: assert False, "error hidden" assert f.calls == [2] and values == [2]
Why is a formatter object not a base class of the report function?
The report uses a collaborator; it is not itself a formatter. One explicit handoff keeps the roles separate. Summing n integers takes O(n) arithmetic steps and constant aggregation storage, excluding integer-size and formatter costs.
Compose a live reader
Return an object with read() that delegates to base.read() once per call and multiplies that result by factor.
The contract
- base.read() returns an integer; factor is an integer and may be zero or negative.
- Return an object with callable read(); each call must read the live base exactly once and return an exact integer product.
- Keep the supplied base reference. Do not copy it, cache a first reading, change its fields directly, or swallow its errors. The base may update its own call counter.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- One delegated read
class Base: def __init__(self): self.calls = 0 def read(self): self.calls += 1 return 3 b = Base() r = make_scaled_reader(b, 4) assert b.calls == 0 value = r.read() assert type(value) is int and value == 12 and b.calls == 1 - Zero factor still delegates
class Base: def __init__(self): self.calls = 0 def read(self): self.calls += 1 return 7 b = Base() r = make_scaled_reader(b, 0) v = r.read() assert type(v) is int and v == 0 and b.calls == 1 - Negative factor
class Base: def read(self): return 3 r = make_scaled_reader(Base(), -2) v = r.read() assert type(v) is int and v == -6 - Live state, no cache
class Base: def __init__(self): self.value, self.calls = 2, 0 def read(self): self.calls += 1 return self.value b = Base() r = make_scaled_reader(b, 5) a = r.read() b.value = 9 c = r.read() assert type(a) is int and a == 10 and type(c) is int and c == 45 and b.calls == 2 and b.value == 9 - Wrappers own their factors
class Base: def __init__(self): self.calls, self.value = 0, 4 def read(self): self.calls += 1 return self.value b = Base() a, c = make_scaled_reader(b, 2), make_scaled_reader(b, 3) x, y = a.read(), c.read() assert type(x) is int and x == 8 and type(y) is int and y == 12 and b.calls == 2 and b.value == 4 - Read error propagated
class Base: def __init__(self): self.calls = 0 def read(self): self.calls += 1 raise ValueError("offline") b = Base() r = make_scaled_reader(b, 3) try: r.read() except ValueError as error: assert str(error) == "offline" else: assert False, "error hidden" assert b.calls == 1
Why is retaining the base reference intentional rather than an ownership bug?
The changed reading is the point of this live adapter. The wrapper owns its multiplier but collaborates with the supplied source. Each read adds constant-size arithmetic and delegation work beyond the base's own cost; it does not copy source state.
Transfer: render an ordered group of totals
The requirement changes from one total to one formatted entry per named group. Keep group order and format empty groups too.
The contract
- groups is a dict from string labels to lists of integers, in desired output order.
- Return an exact list of (label, formatted_text) tuples in dictionary insertion order; format each group's sum exactly once.
- An empty mapping returns []; an empty group still formats zero. Preserve the mapping, lists, duplicates and labels. Do not replace or silence the formatter.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Group order and exact shape
from types import SimpleNamespace seen = [] f = SimpleNamespace(format=lambda n: (seen.append(n), f"<{n}>")[1]) r = render_totals({"z": [2, 3], "a": [1]}, f) assert type(r) is list and r == [("z", "<5>"), ("a", "<1>")] and all(type(p) is tuple and type(p[1]) is str for p in r) and seen == [5, 1] - No groups
from types import SimpleNamespace seen = [] f = SimpleNamespace(format=lambda n: (seen.append(n), str(n))[1]) r = render_totals({}, f) assert type(r) is list and r == [] and seen == [] - Empty group is present
from types import SimpleNamespace seen = [] f = SimpleNamespace(format=lambda n: (seen.append(n), str(n))[1]) r = render_totals({"empty": []}, f) assert type(r) is list and r == [("empty", "0")] and type(r[0]) is tuple and seen == [0] - Repeated values and signed totals
from types import SimpleNamespace seen = [] f = SimpleNamespace(format=lambda n: (seen.append(n), str(n))[1]) r = render_totals({"": [2, 2], "n": [-3, 1]}, f) assert type(r) is list and r == [("", "4"), ("n", "-2")] and all(type(p) is tuple for p in r) and seen == [4, -2] - Nested input ownership
from types import SimpleNamespace values = [3, 1, 3] groups = {"b": values, "a": []} seen = [] f = SimpleNamespace(format=lambda n: (seen.append(n), f"v{n}")[1]) r = render_totals(groups, f) assert type(r) is list and r == [("b", "v7"), ("a", "v0")] and all(type(p) is tuple for p in r) and seen == [7, 0] and list(groups) == ["b", "a"] and groups["b"] is values and values == [3, 1, 3] and groups["a"] == [] - Result container independence
from types import SimpleNamespace f = SimpleNamespace(format=lambda n: str(n)) groups = {"x": [2]} a = render_totals(groups, f) b = render_totals(groups, f) a.append(("later", "9")) assert type(a) is list and a == [("x", "2"), ("later", "9")] and type(b) is list and b == [("x", "2")] and type(b[0]) is tuple and a is not b and groups == {"x": [2]}
Why is this not just formatting one grand total?
The changed contract preserves each label and its position, including empty groups. The solution delegates once per group. With g groups and n total input integers, work is O(g+n) plus formatter costs and result storage is O(g), excluding returned string sizes.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestonesuper follows the MRO
super() continues method lookup through the method resolution order, or MRO. In a cooperative diamond it can reach a sibling, not just the base written beside a class.
Understand first
Optional depth: multiple inheritance sometimes combines independent behaviors. Before using it, understand why a hard-coded parent call can skip a sibling or run a shared ancestor twice.
Words you will see
- MRO
- The consistent class order Python uses to search for methods.
- Diamond
- Two base paths that meet at a common ancestor.
- Cooperative method
- A method that follows agreed signatures and delegates with super so others can participate.
Follow this receiver's order
Both inherits from Left then Right. Its MRO is Both, Left, Right, Root, object. Both has no run, so lookup finds Left.run. super() there continues after Left in this receiver's MRO and finds Right, even though Left's written base is Root.
Right then delegates to Root, which supplies the terminal result. List concatenations add left and right before root in the returned list. This example constructs a result; it is not instrumented timing or a live event trace.
Cooperation needs an agreement
Each participating run takes the same arguments and calls super once. The endpoint Root deliberately stops the chain. Naming Root.run(self) inside Left would skip Right in this receiver's chain.
Do not add multiple inheritance merely to avoid a few duplicated lines. Composition is often easier to reason about. Where a framework requires cooperative methods, document the signature, forwarding and terminal behavior. Inspect __mro__ rather than guessing from source-file order.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
class Both(Left, Right):Choose Left before Right in a shared-ancestor hierarchy.
return ["left"] + super().run()For Both, continue from Left to Right.
return ["right"] + super().run()Continue from Right to Root.
print([cls.__name__ for cls in Both.__mro__])Display the actual class lookup order by stable names.
super is not simply 'call my parent by name'; it continues lookup through the method resolution order. Cooperative multiple inheritance needs compatible signatures and consistent super calls. Inspect the MRO rather than guessing which base method runs.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Reverse the base order.
Try: Use class Both(Right, Left).
The result and displayed MRO put Right before Left.
Show what a named parent skips.
Try: Replace super().run() in Left with Root.run(self).
The result becomes ['left', 'root']; Right is bypassed.
Before you move on
What result does class Reverse(Right, Left) produce from run?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
['right', 'left', 'root']. Reversing the declared base order changes the MRO while the shared Root still runs once.
Control extension points
An extension point is a deliberately replaceable part of an object's behavior. Keep the stable rule outside the part that callers are allowed to replace.
Understand first
Optional depth: replacing behavior is safe only when the replaceable portion has a narrow contract. Here the extension point formats a computed number, not the aggregation policy.
Words you will see
- Extension point
- A documented operation callers may replace.
- Callable
- An object that can be invoked with parentheses, including a function.
- Integration check
- A check of how collaborating parts exchange data, not just each part in isolation.
Keep the seam small
This Report accepts a callable instead of an object with format. Those are different interfaces; callers must know which one is expected. render computes a total and calls the supplied function once with that number.
format_total appends the received number to seen and returns text. seen is deliberately shared observation state in this small example, not a production logging mechanism. Printing [8] proves the handoff value and call count for the original input.
Test what replacement must preserve
A formatter can choose text but should not be responsible for summing the input. Passing it the list would expose input mutation and change the agreed boundary. A test should assert both returned text and that the caller's values remain unchanged.
If the callable raises, let the caller observe the error unless the report has an explicit recovery contract. Do not silently substitute a default formatter. A free function is enough for stateless formatting; a formatter object helps when configuration or state belongs together.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
total = sum(values)Compute the report's stable aggregation rule.
return self.formatter(total)Invoke the injected callable exactly once.
seen.append(total)Record the received scalar for this demonstration.
print(values)Show that reading and formatting did not change the source list.
Document what subclasses may override and which invariants must remain true. A small protocol and composition often reduce coupling. Inheritance does not remove the need for integration tests at the collaborating-object boundary.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Render twice.
Try: Add another Report(format_total).render(values) call before the prints.
seen contains two eights because each render invokes the callable once.
Surface a collaborator error.
Try: Replace return f"{total} units" with raise ValueError("format failed").
Execution raises the explicit error; Report has no silent fallback.
Before you move on
If the formatter returns None, should Report quietly replace it with an empty string?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. That would hide a collaborator contract failure. Specify and test a string result, or explicitly design a different result policy.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.