Sobes.tech
Junior — Middle

How does the use of the __slots__ attribute affect the behavior and performance of classes in Python?

sobes.tech AI

Answer from AI

The __slots__ attribute in Python is used to restrict the set of attributes that instances of a class can have and to optimize memory usage.

By default, each object has a __dict__ dictionary where all attributes are stored. This is flexible but consumes memory.

If you define __slots__ in a class, Python will create a fixed set of attributes and will not create a __dict__ for each instance, which:

  • Reduces memory consumption, especially with a large number of objects.
  • Slightly speeds up attribute access.

However, with __slots__, you cannot dynamically add new attributes that are not listed.

Example:

class Point:
    __slots__ = ('x', 'y')

    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)
 p.x = 10  # works
# p.z = 5  # will raise AttributeError

Thus, __slots__ is useful for optimization when the set of attributes is fixed.