Q18: What is __slots__ and how does it reduce instance memory usage?
By default, Python instances store attributes inside a dynamic __dict__ dictionary (causing memory overhead). Declaring __slots__ = ('attr1', 'attr2') replaces __dict__ with a fixed-size compact array layout, reducing instance memory footprint by up to 60-80%.
Key Takeaways
- Eliminates per-instance
__dict__dynamic dictionary allocations. - Drastically lowers memory footprint for classes instantiated millions of times.
Knowledge Check
Can you assign arbitrary new attribute names to an instance of a class that defines __slots__?