topskill.dev
CoursesTracks
0
All courses/Object Oriented Programming with PythonCompose a service from a collaborator
Inheritance and composition
7 / 13
← Object Oriented Programming with Python
○Define a class○Create two objects○Attach instance data○Read and update data○Class defaults○Shadow a class default○Write an instance method○Return a value○Initialize an object○Constructor defaults○Independent instance lists○Class body scope✦Module Quiz
○Bound methods○Function attributes○Classes are callable○A class method factory○Static methods○The property function○The property decorator○Computed properties○Read-only properties○Property setters✦Module Quiz
○Give objects a friendly string○Make repr useful for debugging○Add two value objects○Subtract value objects○Multiply a value by a scalar○Support reflected multiplication○Compare objects by value○Order value objects○Give an object a length○Choose an object truth value○Build a safe hashable key○Make an instance callable○Customize formatted output○Keep cleanup explicit✦Module Quiz
○Inherit an existing method○Recognize the object base○Extend initialization with super○Override one behavior○Extend a method through super○Substitute objects in a loop●Compose a service from a collaborator○Reserve attributes with slots○Keep slots in a subclass○Combine small inherited capabilities○Inspect method resolution order○Cooperate through a diamond✦Module Quiz
○Start an animal record○Record a rescued bird○Record a rescued fish○Give each animal a movement○Add a feeding service○Keep a rescue register○Group animals by habitat○Print the daily care report✦Module Quiz
○Open an account in cents○Deposit money○Withdraw available money○Add savings account data○Allow a current-account overdraft○Lock a fixed deposit○Calculate simple interest separately○Credit calculated interest○Register accounts by ID○Print a current statement✦Module Quiz
○Name a fixed set of statuses○Choose explicit enum values○Generate internal values with auto○Compare members, not raw codes○Reject duplicate enum values○Iterate over canonical members○Give enum members a method○Choose an enum truth rule○Check the enum type at a boundary○Describe a small dataclass record○Store an enum member in a dataclass○Use dataclass objects as enum values✦Module Quiz
○Intercept an attribute read○Handle class-level descriptor access○Intercept an attribute assignment○Keep descriptor storage per instance○Delete a managed value○Let the class supply a field name○Give a data descriptor priority○Allow a non-data descriptor override○Recognize property as a descriptor○Connect function binding to descriptors○Reuse one validation rule across fields○Initialize a descriptor-backed record✦Module Quiz
○Reject an invalid lobby size○Catch only the expected lookup error○Name a domain error○Carry useful exception details○Preserve the cause of a failure○Release a resource with finally○Declare an abstract contract○Implement a credit fee policy✦Module Quiz
○Validate a product record○Build a searchable catalog○Calculate a cart line○Add products to a cart○Remove a cart line○Summarize the cart○Freeze an order snapshot○Checkout without losing the cart○Register and track an order○Format invoice lines○Render the complete invoice○Route shop commands○Run a scripted shopping session○Launch the console shop✦Module Quiz

Compose a service from a collaborator

The quest HUD uses a formatter, but it is not a formatter. Store that helper on QuestHUD and ask it to format each message. The HUD here is a text-only object, so you can replace its helper without building a UI or another inheritance tree.

The supplied QuestHUD initializer receives a formatter object and stores it as self.formatter. Passing a dependency into an object instead of constructing it internally is often called dependency injection. Here it is just an ordinary constructor argument. The benefit is concrete: the caller can supply a different formatter while the HUD keeps the same publishing behavior.

Your publishing method should ask the stored collaborator to format the incoming text and pass its result back to the caller. The HUD does not need to know the formatter's concrete type or how it builds the text. It only relies on the small interface: a format method accepting one text argument and returning a string.

The example shows a playlist containing a speaker. The playlist calls a method on that separate object; it does not inherit from the speaker. Notice the two dots in self.speaker.play(title): first retrieve the collaborator, then call its behavior. The exercise uses that same relationship with text formatting rather than playback.

Inheritance is still useful when a specialized object can stand in for its base. Composition is useful when responsibilities are separate or the collaborator may vary independently. Do not make QuestHUD a subclass of its formatter simply to reach the format method.

The tests pass different collaborators and replace one on an existing HUD. They also count calls to detect duplicate formatting. Do not create a new BracketFormatter inside publish, because doing so would ignore the supplied dependency and make replacement ineffective. The returned message should come directly from the current collaborator.

A small example

python
class Speaker:
    def play(self, title):
        return f"Playing {title}"

class Playlist:
    def __init__(self, speaker):
        self.speaker = speaker

    def start(self, title):
        return self.speaker.play(title)

print(Playlist(Speaker()).start("Rain"))

Picture the behavior

The diagram uses a separate example: MatchService asks an injected ScoreRule for score(points). Your QuestHUD delegates text formatting instead. Both examples keep the helper separate from its caller and run entirely in memory.

Your Task

  1. Implement QuestHUD.publish(text) to call the current formatter's format(text) exactly once and return its result. Use the injected collaborator instead of constructing or inheriting a formatter.

Edit main.py and use Run to inspect the supplied check. Leave that check unchanged; Submit tests your method with other values too.

Hint 1
1 / 1
HINT 1

Read self.formatter on every call so collaborator replacement takes effect.

Files
  • ⋄main.py
Loading editor…
Press Run to execute your code.