slots — restrict instance attributes to a fixed set, reducing memory.
1class PointWithSlots:2 __slots__ = ("x", "y")34 def __init__(self, x, y):5 self.x = x6 self.y = y78p = PointWithSlots(1, 2)9print(p.x, p.y) # 1 210# p.z = 3 # AttributeError: 'PointWithSlots' object has no attribute 'z'1112# Memory comparison13import sys1415class Regular:16 def __init__(self, x, y):17 self.x = x18 self.y = y1920r = Regular(1, 2)21s = PointWithSlots(1, 2)22print(sys.getsizeof(r.__dict__)) # ~104 bytes23# s has no __dict__ attribute
Benefits:
Trade-offs: