topskill.dev
CoursesTracks
0
All courses/Object Oriented Programming with PythonComputed properties
Object interfaces
8 / 11
← 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

Computed properties

An item pool tracks a total count and how many items are currently equipped. The unequipped items are available. Calculate that count when it is read rather than maintaining a third counter that could fall out of sync.

Derive rather than duplicate

python
class QuestProgress:
    def __init__(self, planned, completed):
        self.planned = planned
        self.completed = completed

    @property
    def remaining(self):
        return self.planned - self.completed

The getter reads two ordinary instance attributes and returns their difference. There is no self.remaining assignment in the initializer. Changing completed automatically affects the next reading because the calculation runs again.

A property does not cache its result by default. If you read it twice, the getter executes twice. That is useful here because the calculation is cheap and the source values may change between reads. Storing the result once would make sense only if you deliberately wanted a snapshot rather than a current view.

Keep one source of truth for each fact. In the quest example, planned and completed steps are stored facts; remaining steps are derived from them. Updating a derived counter separately would create opportunities for contradictory state, such as totals that no longer agree.

For the exercise, each pool's total and equipped instance attributes are the supplied stored facts. Assume they are nonnegative integers with equipped no greater than total. You do not need to reject invalid input or clamp a negative result. Those would be different contracts and could hide a mistake in the source data.

Add the available property yourself, including its decorator and getter. The probe changes equipped between reads. Leave that change in place: a correct first number alone cannot distinguish a live computation from a value copied during initialization. Submit also checks an empty pool and two separate pools to keep the calculation tied to the receiving instance.

Your Task

  1. Add a read-only ItemPool.available property that returns the current total minus equipped, calculating the value on every access.

Run and check

Edit main.py. Press Run to inspect the supplied console probe, then Submit to check your implementation. The completed probe reports 7, then 4.

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