topskill.dev
CoursesTracks
0
All courses/Object Oriented Programming with PythonIntercept an attribute assignment
Descriptors
3 / 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

Intercept an attribute assignment

A mana pool must reject negative amounts. A descriptor setter can enforce that rule whenever code assigns to the public field.

Define __set__(self, instance, value) on the descriptor type to intercept instance.field = value. Here self is still the shared helper, instance is the record being changed, and value is the proposed new value. The setter normally stores data and returns nothing useful to the assignment statement.

Validate before writing. raise ValueError("message") stops the assignment and tells the caller that the proposed value is unacceptable. If the old value must survive a rejected update, perform the check before changing storage. The later errors module studies exception design in more detail; this task needs only that simple rejection rule.

The example strips surrounding spaces from a text label and stores it under a different attribute name. The strip() string method returns a cleaned string without changing the original. Writing instance.label = value from the setter for label would call the same setter again. A separate backing attribute avoids that recursion. The exercise supplies a getter that reads its backing attribute, so the read/write pair must agree about storage.

This class uses ordinary instance dictionaries, not __slots__. The backing attribute belongs to each record. The descriptor itself should hold the rule, not a single mana amount shared by all records. The next lesson examines that distinction more closely.

You only need to handle numeric mana amounts in this exercise; fractional amounts are allowed. Do not add unrelated string conversion or type policies. The visible probe tries a successful update and then a negative one, making the preservation of the last accepted value observable.

A small example

python
class TrimmedPlayerName:
    def __set__(self, instance, value):
        instance._saved = value.strip()

class PlayerProfile:
    label = TrimmedPlayerName()

profile = PlayerProfile()
profile.label = "  Mira  "
print(profile._saved)

Your Task

  1. Implement ManaAmount.__set__ to reject negative numbers with ValueError and otherwise store the value in instance._mana, leaving the previous value unchanged after rejection.

Edit main.py, then press Run to inspect the supplied probe. Submit checks the task with additional cases. You do not need to change the probe.

Hint 1
1 / 1
HINT 1

Check value before assigning the backing attribute used by the getter.

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