15. Slot Classes
Summary of Benefits:
Memory Efficiency:
__slots__allows you to define a fixed set of attributes, eliminating the overhead of the default__dict__storage.Faster Attribute Access: By avoiding the dictionary lookup, attribute access can be faster.
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__
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 22. Memory Optimization with __slots__
import sys
class Person:
__slots__ = ['name', 'age']
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 30)
print(sys.getsizeof(person)) # Memory usage for an instance with __slots__
# Without __slots__
class PersonWithoutSlots:
def __init__(self, name, age):
self.name = name
self.age = age
person_no_slots = PersonWithoutSlots("John", 30)
print(sys.getsizeof(person_no_slots)) # Memory usage without __slots__3. Preventing Dynamic Attribute Assignment
4. Using __slots__ with Inheritance
5. __slots__ in Combination with __dict__
6. Using __slots__ for Larger Classes
7. Dynamic Behavior with __slots__
8. Memory Usage Comparison Between __slots__ and Normal Classes
9. __slots__ with Class Variables
10. Trying to Add New Attributes to a Class with __slots__
Last updated