How do I use slots to reduce memory in classes?

In Python, the use of __slots__ allows you to explicitly declare data members for your classes, which can lead to significant memory savings, especially when dealing with a large number of instances. By default, Python uses a dictionary to store instance attributes, which can consume more memory. Declaring __slots__ informs Python that only a fixed set of attributes will be used, thus optimizing memory usage.

Example

class MyClass: __slots__ = ['name', 'age'] # Declare slots for attributes def __init__(self, name, age): self.name = name self.age = age # Create instances obj1 = MyClass('Alice', 30) obj2 = MyClass('Bob', 25) # Memory usage comparison print(f'Object 1: {obj1.name}, Age: {obj1.age}') print(f'Object 2: {obj2.name}, Age: {obj2.age}')