Optimizing Classes with `__slots__`
OOP Modern Tools
Using __slots__
`__slots__` tells Python to allocate a fixed set of attributes, eliminating the per-instance `__dict__`.
Definition
class LightPoint:
__slots__ = ("x", "y", "z")
def __init__(self, x: float, y: float, z: float):
self.x = x
self.y = y
self.z = z
- Prevents creation of new attributes outside
__slots__. - Reduces memory footprint and speeds attribute lookup.
Trade-offs
- Incompatible with
__dict__by default; add'__dict__'if you need dynamic attrs. - Doesn't play nicely with multiple inheritance unless all parents define slots.
- Use when instantiating thousands of lightweight objects or running in tight loops.