Middle+
What is __slots__ in Python?
sobes.tech AI
Answer from AI
__slots__ in Python is a mechanism that allows you to restrict the set of attributes that instances of a class can have, thereby saving memory.
By default, each object has a __dict__ dictionary where all attributes are stored. This is convenient but consumes additional memory. If you declare __slots__ in a class, Python does not create a __dict__ for instances but allocates a fixed set of attributes.
Example:
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(p.x, p.y) # 1 2
# p.z = 3 # will raise AttributeError because 'z' is not in __slots__
Using __slots__ is useful when creating many objects of the same class and memory optimization is important. However, it restricts the dynamic addition of new attributes.