slots — memory and access time savings.
1import sys23class Regular:4 def __init__(self, x, y):5 self.x = x6 self.y = y78class Optimized:9 __slots__ = ("x", "y")1011 def __init__(self, x, y):12 self.x = x13 self.y = y1415# Object size16r = Regular(1, 2)17o = Optimized(1, 2)18print(f"Regular: {sys.getsizeof(r) + sys.getsizeof(r.__dict__)} bytes")19print(f"Optimized: {sys.getsizeof(o)} bytes")20# Regular: ~152 bytes21# Optimized: ~56 bytes2223# Access speed24import timeit25print(timeit.timeit(lambda: r.x, number=1000000)) # Slower26print(timeit.timeit(lambda: o.x, number=1000000)) # Faster
When to use: