Junior — Middle
What is the role of the slots method and what advantages does it provide in resource optimization?
sobes.tech AI
Answer from AI
In Python, the __slots__ method is used to restrict the set of attributes for class instances. It allows explicitly specifying which attributes can belong to an object, thereby:
- Saving memory, as objects do not create a dynamic
__dict__to store attributes. - Speeding up attribute access due to a fixed structure.
Example of usage:
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 an attribute not specified in __slots__
Thus, __slots__ is useful for memory optimization and performance enhancement, especially when creating a large number of objects.