InterviewHubPRO
Section Overview
Q18

Question 18 of 65

Part 2: Python Core Language, Internals & Runtime (6 - 25)

28%
Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)

`__slots__` and memory reduction:

In Simple Words: By default, Python objects store attributes in a dynamic dictionary (__dict__). Defining __slots__ prevents __dict__ creation, allocating fixed array pointers and saving up to 60% RAM for millions of objects.

python
class PointWithSlots:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = PointWithSlots(10, 20)
# p.z = 30  # Raises AttributeError: 'PointWithSlots' object has no attribute 'z'