Sobes.tech
Junior — Middle

What happens to the class's working mechanism after declaring __slots__?

sobes.tech AI

Answer from AI

After declaring the __slots__ attribute in a class, Python stops using the standard __dict__ dictionary to store instance attributes. Instead, a fixed set of attributes specified in __slots__ is allocated, which are stored in a more compact structure. This leads to reduced memory consumption and faster attribute access, but imposes restrictions: you cannot dynamically add new attributes not listed in __slots__, and the class will not have a __dict__ attribute (unless explicitly added to __slots__).

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 because 'z' is not in __slots__