Sobes.tech
Junior — Middle

How does a class using __slots__ differ from a regular class without it?

sobes.tech AI

Answer from AI

A class using __slots__ in Python restricts the set of attributes that instances of this class can have. This allows:

  • Saving memory, as a __dict__ dictionary is not created for each object.
  • Faster attribute access.

In a regular class, each object stores its attributes in a __dict__ dictionary, which provides flexibility but requires more memory and time to look up attributes.

Example:

class WithoutSlots:
    def __init__(self, x):
        self.x = x

class WithSlots:
    __slots__ = ['x']
    def __init__(self, x):
        self.x = x

obj1 = WithoutSlots(10)
obj2 = WithSlots(10)

print(hasattr(obj1, '__dict__'))  # True
print(hasattr(obj2, '__dict__'))  # False

Thus, __slots__ is useful when you need to optimize memory and restrict the set of attributes, but it reduces the flexibility of the class.