Lock Down Attributes with __slots__

Hard ⏱ 18 min 30% acceptance ★★★★★ 4.8
Define Pixel with __slots__ = ('x', 'y') and a constructor setting both. Slots remove the per-instance __dict__ (saving memory across millions of instances) and make assigning any *other* attribute raise AttributeError — write try_extra(pixel) returning 'rejected' when setting pixel.z = 1 fails.

Examples

Example 1
Input
try_extra(Pixel(1, 2))
Output
'rejected'
Explanation

z is not in __slots__, so assignment raises.

Constraints

  • Declare __slots__ as shown.
  • Catch AttributeError in try_extra.

Topics

OOP__slots__

Companies

MetaDropboxReddit

Hints

Hint 1

Slots are declared in the class body as a tuple of names.

Hint 2

try/except AttributeError around the assignment.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.