__slots__

Memory optimization for classes

Interview Relevant: Performance optimization

__slots__

Optimize memory by restricting attributes.

Code Examples

Using __slots__ for memory efficiency.

python
1class WithoutSlots:
2    def __init__(self, x, y):
3        self.x = x
4        self.y = y
5
6class WithSlots:
7    __slots__ = ['x', 'y']
8    def __init__(self, x, y):
9        self.x = x
10        self.y = y
11
12# Memory comparison
13import sys
14a = WithoutSlots(1, 2)
15b = WithSlots(1, 2)
16# WithSlots uses less memory (no __dict__)
17
18# Cannot add new attributes
19b.z = 3  # AttributeError!
20
21# No __dict__ available
22hasattr(a, '__dict__')  # True
23hasattr(b, '__dict__')  # False
24
25# Slots with inheritance
26class Child(WithSlots):
27    __slots__ = ['z']  # Add more slots

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In