Junior — Middle
Explain the concept of slots in Python and what they are used for.
sobes.tech AI
Answer from AI
In Python, __slots__ is a mechanism that allows you to restrict the set of attributes that instances of a class can have, thereby saving memory.
By default, class instances store their attributes in a __dict__ dictionary, which consumes additional memory. If you define an attribute __slots__ in a class as a tuple of allowed attribute names, Python will not create a dictionary for each object but will allocate a fixed space for the specified attributes.
This is useful when creating a large number of objects and memory optimization is important.
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__
Thus, __slots__ helps save memory and prevents the dynamic addition of new attributes.