Python __slots__
The __slots__
attribute in Python is used to define the attributes of a class and restricts the creation of any additional attributes. It is a technique used to optimize memory usage and improve attribute access speed.
By using __slots__
, we can define a fixed set of attributes for instances of a class. This is achieved by assigning a tuple of attribute names to the __slots__
attribute within the class definition. The attribute names listed in __slots__
will be the only attributes allowed for instances of the class, and any attempt to assign a value to an attribute that is not listed will raise an AttributeError
.
Here is an example that demonstrates the use of __slots__
:
class Person:
__slots__ = ('name', 'age')
def __init__(self, name, age):
self.name = name
self.age = age
person = Person('John', 25)
person.name = 'Jane' # This is allowed since 'name' is defined in __slots__
person.age = 30 # This is allowed since 'age' is defined in __slots__
person.gender = 'Male' # This will raise an AttributeError since 'gender' is not defined in __slots__
In the above example, the Person
class defines the name
and age
attributes in the __slots__
attribute. This means that instances of the Person
class can only have these two attributes. Any attempt to assign or access attributes not listed in __slots__
will result in an AttributeError
.
Using __slots__
can be beneficial in situations where we are working with a large number of instances of a class and want to reduce memory usage by not storing a __dict__
attribute for each instance. Additionally, attribute access can be faster when using __slots__
since the attribute lookup is simplified.