Usage of __slots__?
__slots__
is a way to specify a fixed set of attributes for a class, which can help to save memory in certain situations. Instead of having a dynamic dictionary for each instance to store its attributes, instances of a class with __slots__
defined will only have space allocated for the attributes listed in __slots__
. This can be useful when you have a large number of instances and want to save memory.
Here is an example of a class that uses __slots__
:
class MyClass:
__slots__ = ['a', 'b']
def __init__(self, a, b):
self.a = a
self.b = b
obj = MyClass(1, 2)
print(obj.a) # 1
print(obj.b) # 2
In this example, MyClass
uses __slots__
to specify that instances of the class should only have space allocated for the attributes a
and b
. Attempting to set an attribute not in slots will raise AttributeError.
obj.c = 3 # AttributeError: 'MyClass' object has no attribute 'c'
Note that __slots__
only affects the space consumption of instances of the class and not the class itself. It also disables the creation of instance dictionary, so you can't add new attributes to the class instances after they're created.