topskill.dev
CoursesTracks
0
All courses/Object Oriented Programming with PythonReserve attributes with slots
Inheritance and composition
8 / 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

Reserve attributes with slots

A map cell should hold exactly a row and column. A typo such as cell.colum = 8 should fail instead of creating an unrelated field. Use __slots__ to give MapCell a fixed layout.

Ordinary user-defined instances usually store their attributes in a dictionary named __dict__. A class-level __slots__ declaration names storage locations instead. For a plain class whose bases do not already supply a dictionary, declaring slots without __dict__ prevents arbitrary additional attributes. The initializer can still assign the listed fields normally.

Use a tuple of attribute-name strings. Those names describe storage, not the values to put there. They belong in the class body, alongside methods, rather than inside __init__. A slotted field remains mutable unless you add a separate policy; slots do not freeze an object or validate whether a coordinate is positive.

The example reserves one field for a dial. Its initializer and later reassignment use familiar dot notation. The exercise needs two fields, so your declaration must include both. Omitting one makes the supplied initializer fail with AttributeError, which reports an unavailable attribute. Assigning an unlisted name raises the same exception. The later errors module covers catching and designing exceptions in more depth.

Slots can reduce per-instance overhead when many small objects exist, but this lesson makes no particular memory or speed promise. The visible benefit here is a constrained layout. They also affect subclass behavior, which the next lesson handles; do not assume a parent's slots automatically restrict every future subclass.

Keep the coordinate initializer unchanged. Run prints the valid fields and attempts one extra field inside a supplied try/except probe. Before your change that extra assignment succeeds; afterward the probe should report that it was rejected. Submit also confirms that the two legitimate fields can still be updated.

A small example

python
class Dial:
    __slots__ = ("position",)

    def __init__(self, position):
        self.position = position

control = Dial(3)
control.position = 5
print(control.position)

Your Task

  1. Add __slots__ to MapCell for exactly row and column, without an instance dictionary. Both fields must remain assignable, while extra attributes raise AttributeError.

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

Declare the names in the class body; do not change the initializer.

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