__slots__ special attribute | Python3.9 | Python tutorial for absolute beginners in Hindi

Опубликовано: 24 Март 2026
на канале: CodeWithRajat
263
2

_slots_ special attribute | Python3.9 | Python tutorial for absolute beginners in Hindi

The special attribute _slots_ allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:

faster attribute access.
space savings in memory.
The space savings is from

Storing value references in slots instead of __dict__.
Denying _dict_ and _weakref_ creation if parent classes deny them and you declare __slots__.


Requirements:
To have attributes named in _slots_ to actually be stored in slots instead of a __dict__, a class must inherit from object.

To prevent the creation of a _dict__, you must inherit from object and all classes in the inheritance must declare __slots_ and none of them can have a '__dict__' entry.

There are a lot of details if you wish to keep reading.

Why use __slots__: Faster attribute access.
The creator of Python, Guido van Rossum, states that he actually created _slots_ for faster attribute access.