topskill.dev
CoursesTracks
0
All courses/Object Oriented Programming with PythonGive objects a friendly string
Python protocols
1 / 15
← 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

Give objects a friendly string

Mosslight Studio needs readable map markers for Lantern Vale. The previous section gave objects explicit interfaces; now you will let Python operations such as str() use those interfaces. Give MapMarker a label showing its destination and distance.

A protocol is an agreement about behavior. Python recognizes certain method names and uses them for familiar operations. These names have two underscores on each side; programmers often call them dunder methods. __str__(self) is the protocol method for a friendly text representation. Calling str(marker) asks the object for that text, and print(marker) uses it too. The result must be a string, even when some stored attributes are numbers.

Do not print inside __str__. Printing is a side effect; returning a string lets the caller decide whether to print it, put it in a message, or save it for later. A missing return produces None, which is not a valid result for this protocol. An f-string is convenient because it converts embedded values to text while keeping the surrounding label readable.

The small example uses a kitchen timer. Notice that the method reads the current instance rather than a global variable. Two timers can therefore produce different descriptions with the same method definition. Your map markers need the same independence, but a different output format.

Special methods belong on the class, alongside __init__, rather than being assigned to a single instance. Keep the supplied initializer unchanged. After implementing the method, also try changing a marker's distance and printing it again: a useful description reflects the current data instead of caching the first label.

A small example

python
class Timer:
    def __init__(self, minutes):
        self.minutes = minutes

    def __str__(self):
        return f"Timer: {self.minutes} min"

print(Timer(7))

Your Task

  1. Implement MapMarker.__str__ to return <destination>: <km> km, using the current attributes. For example, the supplied marker should print Lake: 4 km.

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

Return text; leave printing to the supplied probe.

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