Predict the Output: Slots Restriction
Beginner · Predict the output · from Python __slots__: Reduce Memory Usage by 40%
From the lesson: Python __slots__: Reduce Memory Usage by 40%
Imagine a parking lot. A normal Python object is like an open field where cars can park anywhere. Flexible, but wasteful - you need a huge space even if only a few cars show up.
Read the lessonRead the code carefully. What will be printed? Think about what happens when you try to set an attribute that is not listed in __slots__.
class Box:
__slots__ = ('width', 'height')
def __init__(self, w, h):
self.width = w
self.height = h
b = Box(10, 20)
print(b.width)
try:
b.depth = 5
print(b.depth)
except AttributeError:
print('No dynamic attrs!')
More __slots__ exercises
- Create a Slotted ClassBeginner
- Fix the Bug: Missing SlotIntermediate
- Slots with InheritanceAdvanced
- Compare Memory: Regular vs SlottedAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz