How to use __slots__ in Python

__slots__ in Python class prevents dynamic creation of attributes. In this tutorial we will see how to create dynamic attributes for object of class, than we will prevent creation of dynamic attributes by using __slots__. Lets understand both of the scenarios with below code snippets.

Create a class, instantiate object and create dynamic attribute with the object


class Student(object):

    def __init__(self, name, age, subjects):
        self.name = name
        self.age = age
        self.subjects = subjects

    def __str__(self):
        return f"Student {self.name} is having subjects {self.subjects}"

student1 = Student("ABC", 20, ["Maths", "Physics"])

print(student1)

## Creating dynamic attribute rollno with object student1
student1.rollno = 101
print(student1.rollno)

Output


Student ABC is having subjects ['Maths', 'Physics']
101

From the output we can see we are able to add new attribute rollno without any issue, now we will prevent this by implementing __slots__ in Student class.


class Student(object):

    # Define attribute list with __slots__
    __slots__ = ['name', 'age', 'subjects']

    def __init__(self, name, age, subjects):
        self.name = name
        self.age = age
        self.subjects = subjects

    def __str__(self):
        return f"Student {self.name} is having subjects {self.subjects}"

student1 = Student("ABC", 20, ["Maths", "Physics"])

print(student1)

# This will throw an error as rollno is not included in __slots__
student1.rollno = 101
print(student1.rollno)


Output:


Student ABC is having subjects ['Maths', 'Physics']
Traceback (most recent call last):
  File "C:/Users/***/**.py", line 17, in >module>
    student1.rollno = 101
AttributeError: 'Student' object has no attribute 'rollno'


__slots__ prevented creation of dynamic attribute and generated AttribtuteError


Follow US on Twitter: