168. __slots__ for Memory EfficiencyPage 4

Snippet 1: Basic Usage of __slots__

Copy

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__

Copy

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

Copy


Snippet 4: Using __slots__ in Inheritance (Single Level)

Copy


Snippet 5: Combining __slots__ with Class Variables

Copy


Snippet 6: Attempting to Use __dict__ with __slots__

Copy


Snippet 7: Using __slots__ with Properties

Copy


Snippet 8: Multiple Inheritance and __slots__

Copy


Snippet 9: Performance Measurement with __slots__

Copy


Snippet 10: Extending __slots__ Dynamically (Workaround)

Copy


Last updated