15. Slot Classes

Summary of Benefits:

  1. Memory Efficiency: __slots__ allows you to define a fixed set of attributes, eliminating the overhead of the default __dict__ storage.

  2. Faster Attribute Access: By avoiding the dictionary lookup, attribute access can be faster.

  3. Prevention of Dynamic Attributes: Helps prevent accidental creation of new attributes.

This technique is particularly beneficial when you're working with a large number of objects and need to save memory, such as in data-driven applications or high-performance computing.


1. Basic Use of __slots__

Copy

class Point:
    __slots__ = ['x', 'y']  # Define allowed attributes

    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)
print(p.x, p.y)  # Output: 1 2

2. Memory Optimization with __slots__

Copy


3. Preventing Dynamic Attribute Assignment

Copy


4. Using __slots__ with Inheritance

Copy


5. __slots__ in Combination with __dict__

Copy


6. Using __slots__ for Larger Classes

Copy


7. Dynamic Behavior with __slots__

Copy


8. Memory Usage Comparison Between __slots__ and Normal Classes

Copy


9. __slots__ with Class Variables

Copy


10. Trying to Add New Attributes to a Class with __slots__

Copy

Last updated