Junior — Middle
Explain the purpose and principle of the __slots__ attribute 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. This allows:
- Saving memory, as a
__dict__dictionary is not created for each object. - Slightly speeding up attribute access.
How it works:
When you declare __slots__ in a class, you specify a fixed set of attribute names. Python creates a special internal storage for them instead of a regular dictionary.
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 # Error: cannot add attribute not specified in __slots__
Restrictions:
- Cannot dynamically add new attributes not specified in
__slots__. - Not suitable if a flexible set of attributes is needed.
- Not compatible with some inheritance mechanisms unless
__slots__is considered in subclasses.
Used for optimization in cases where many objects with a fixed set of attributes are created.