Junior — Middle
What is the advantage of using __slots__ in Python compared to traditional attribute storage methods?
sobes.tech AI
Answer from AI
Using __slots__ in Python allows you to explicitly specify a fixed set of attributes for class instances, which offers several advantages over the traditional storage of attributes in the __dict__ dictionary:
- Memory savings: Instances with
__slots__do not create a dictionary for attributes but use a more compact internal representation, reducing memory consumption, especially when there are many objects. - Faster attribute access: Access to attributes can be quicker because there is no need to look up in a 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
However, with __slots__, you cannot dynamically add new attributes that are not listed, which limits flexibility but increases performance and saves memory.