Junior — Middle
Explain the use of __slots__ in Python and how it affects object memory management.
sobes.tech AI
Answer from AI
In Python, __slots__ is used to restrict the set of attributes that instances of a class can have. By default, each object has a __dict__ dictionary where all attributes are stored, which consumes additional memory.
When __slots__ is declared in a class, Python does not create a __dict__ for instances but allocates a fixed space for the specified attributes. This reduces memory consumption and can speed up attribute access.
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 # AttributeError, as 'z' is not in __slots__
Thus, __slots__ helps save memory when there are many objects and prevents the dynamic addition of new attributes.