Junior — Middle
What is the purpose of using __slots__ in Python and how does it differ from regular class attributes?
sobes.tech AI
Answer from AI
__slots__ 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. - Speeding up attribute access.
The difference from regular attributes is that when using __slots__, Python knows in advance which attributes are allowed and does not create a dynamic attribute dictionary.
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 = 3 # will raise AttributeError because 'z' is not in __slots__
Thus, __slots__ is useful for memory optimization and preventing accidental addition of new attributes.