168. __slots__ for Memory EfficiencyPage 4
Snippet 1: Basic Usage of __slots__
__slots__class Person:
__slots__ = ('name', 'age')
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(p.name, p.age)
# p.address = "New York" # AttributeError: 'Person' object has no attribute 'address'Snippet 2: Memory Comparison with and without __slots__
__slots__import sys
class WithoutSlots:
def __init__(self, name, age):
self.name = name
self.age = age
class WithSlots:
__slots__ = ('name', 'age')
def __init__(self, name, age):
self.name = name
self.age = age
obj1 = WithoutSlots("Alice", 30)
obj2 = WithSlots("Alice", 30)
print(sys.getsizeof(obj1.__dict__)) # Memory used without __slots__
print(sys.getsizeof(obj2)) # Memory used with __slots__Snippet 3: Preventing Dynamic Attribute Addition
Snippet 4: Using __slots__ in Inheritance (Single Level)
__slots__ in Inheritance (Single Level)Snippet 5: Combining __slots__ with Class Variables
__slots__ with Class VariablesSnippet 6: Attempting to Use __dict__ with __slots__
__dict__ with __slots__Snippet 7: Using __slots__ with Properties
__slots__ with PropertiesSnippet 8: Multiple Inheritance and __slots__
__slots__Snippet 9: Performance Measurement with __slots__
__slots__Snippet 10: Extending __slots__ Dynamically (Workaround)
__slots__ Dynamically (Workaround)Last updated