In this lesson, you will learn how to optimize your class memory usage and enforce strict attribute creation by using the __slots__ attribute.
The Problem: The Hidden Dictionary
By default, every time you create an instance of a class in Python, the interpreter creates a special dictionary called __dict__ to store that instance's attributes. This allows you to add new attributes to an object on the fly (e.g., my_obj.new_attr = 10), which is very flexible. However, this flexibility comes at a cost: storing a dictionary for every single object consumes a significant amount of memory, especially if you are creating thousands or millions of objects.
Restricting with __slots__
If you know exactly which attributes your class needs, you can use __slots__ to tell Python to skip the __dict__ entirely. By defining __slots__, you instruct Python to allocate space only for the specific variables you have listed.
Here is how you implement it:
class Player:
# Only allow these two attributes
__slots__ = ['name', 'score']
def __init__(self, name, score):
self.name = name
self.score = score
p1 = Player("Alice", 100)
# This works fine:
print(p1.name)
# This will raise an AttributeError:
# p1.health = 50
Why use __slots__?
There are two main benefits to this approach:
- Memory Efficiency: Because there is no
__dict__for each instance, your program consumes significantly less RAM when dealing with large collections of objects. - Safety: It prevents the creation of arbitrary or "junk" attributes. If you accidentally misspell an attribute name when assigning it, Python will immediately raise an
AttributeErrorrather than silently creating a new, unintended attribute.
Using __slots__ turns your objects into lean, rigid structures, perfect for performance-critical applications where the shape of your data is well-defined.
Key Takeaway: Using __slots__ optimizes memory and prevents the creation of unauthorized attributes by disabling the instance-specific __dict__.