What is the purpose of the __slots__ keyword in Python?
Python > Python Classes and Objects > Python Introduction to OOP
217
Answer:
The __slots__
keyword in Python is used to define a fixed set of attributes for a class. When a class defines __slots__
, it restricts the creation of instance variables to only those defined in the __slots__
declaration.
The primary purpose of __slots__
is to reduce memory usage and improve performance in situations where many instances of a class need to be created. By restricting the set of possible instance variables, Python can allocate memory more efficiently and avoid the memory overhead of a dictionary that would be used for dynamic attribute storage.
Here's an example to illustrate the use of __slots__
:
class Person: __slots__ = ['name', 'age'] def __init__(self, name, age): self.name = name self.age = age
In this example, the Person
class defines __slots__
to include the name
and age
attributes. This means that instances of the Person
class can only have those two attributes, and any attempts to add new attributes will result in an AttributeError
.
Using __slots__
can offer significant memory savings, especially for classes that create many instances or that have many small attributes. However, it's important to note that __slots__
also has some limitations, such as preventing the use of dynamic attributes and making it harder to subclass the class. Therefore, it's important to use __slots__
judiciously and only when you have a good reason to do so.
This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.