Summary: In this tutorial, you will learn with example the significance of the __slots__ in Python programming language.

__slots__ is a special attribute in Python that allows a programmer to specify which attributes can be assigned to an instance of a class.

It is used to reduce the memory overhead of creating instances, as it allows the interpreter to store the instance variables in a more memory-efficient way.

Conside the following example for instance:

class Point:
    __slots__ = ['x', 'y']
    def __init__(self, x, y):
        self.x = x
        self.y = y

point = Point(1, 2)
point.x  # Output: 1
point.y  # Output: 2
point.z = 3  # This will raise an AttributeError, because 'z' is not in the __slots__ attribute

In the example above, the Point class has __slots__ defined as ['x', 'y'], which means that the only attributes that can be assigned to an instance of this class are x and y.

If you try to assign an attribute that is not in the __slots__ list, you will get an AttributeError exception.

It’s important to note that __slots__ only works for instance variables, and not for class variables.

Also, it is important to note that __slots__ can only be used for classes that do not inherit from other classes. It is because we cannot inherit the __slots__ attribute.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply