Monday, September 29, 2025
HomeLanguagesPython | Use of __slots__

Python | Use of __slots__

When we create objects for classes, it requires memory and the attribute are stored in the form of a dictionary. In case if we need to allocate thousands of objects, it will take a lot of memory space.
slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects.

Example of python object without slots :




class GFG(object):
      def __init__(self, *args, **kwargs):
                self.a = 1
                self.b = 2
  
if __name__ == "__main__":
     instance = GFG()
     print(instance.__dict__)


Output :

{'a': 1, 'b': 2}

As every object in Python contains a dynamic dictionary that allows adding attributes. For every instance object, we will have an instance of a dictionary that consumes more space and wastes a lot of RAM. In Python, there is no default functionality to allocate a static amount of memory while creating the object to store all its attributes.
Usage of __slots__ reduce the wastage of space and speed up the program by allocating space for a fixed amount of attributes.

Example of python object with slots :




class GFG(object):
      __slots__=['a', 'b']
      def __init__(self, *args, **kwargs):
                self.a = 1
                self.b = 2
  
if __name__ == "__main__":
     instance = GFG()
     print(instance.__slots__)


Output :

['a', 'b']

Example of python if we use dict :




class GFG(object):
      __slots__=['a', 'b']
      def __init__(self, *args, **kwargs):
                self.a = 1
                self.b = 2
  
if __name__ == "__main__":
     instance = GFG()
     print(instance.__dict__)


Output :

AttributeError: 'GFG' object has no attribute '__dict__'

This error will be caused.

Result of using __slots__:

  1. Fast access to attributes
  2. Saves memory space
RELATED ARTICLES

Most Popular

Dominic
32324 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6695 POSTS0 COMMENTS
Nicole Veronica
11860 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11918 POSTS0 COMMENTS
Shaida Kate Naidoo
6807 POSTS0 COMMENTS
Ted Musemwa
7073 POSTS0 COMMENTS
Thapelo Manthata
6763 POSTS0 COMMENTS
Umr Jansen
6771 POSTS0 COMMENTS