Compare Memory: Regular vs Slotted
Advanced · Write the code · 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 lessonCreate two classes: RegularVec (no slots) and SlottedVec (with slots). Both should have x and y attributes. Use sys.getsizeof() to measure the size of one instance of each (for RegularVec, add the size of its __dict__; the slotted version has no __dict__). Compare the two sizes and print exactly 'Slotted is smaller' if the slotted version uses less memory.
Note: the exact byte counts vary by Python build, so we only print the comparison result, not the raw sizes.
More __slots__ exercises
- Create a Slotted ClassBeginner
- Predict the Output: Slots RestrictionBeginner
- Fix the Bug: Missing SlotIntermediate
- Slots with InheritanceAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz