Use __slots__ to limit instance attributes and potentially reduce memory.
How It Works
Setting __slots__ to a fixed sequence of field names can eliminate each instance’s normal __dict__, depending on inheritance. Slots restrict spontaneous attributes but are not immutability or an access-control mechanism.
Dataclasses support slots=True for a convenient generated implementation.
Step-by-Step Example
class Coordinate:
__slots__ = ("latitude", "longitude")
def __init__(self, latitude, longitude):
self.latitude = latitude
self.longitude = longitude
location = Coordinate(32.1, 34.8)
print(location.latitude, location.longitude)
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The expression '("latitude", "longitude")' supplies the value stored as '__slots__'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
32.1 34.8
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Create a slotted Point class with x and y fields.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Assuming __slots__ makes existing attributes immutable or private.
- Forgetting that a subclass with a __dict__ can re-enable dynamic attributes.
Key Takeaways
- Use __slots__ to limit instance attributes and potentially reduce memory.
- Setting __slots__ to a fixed sequence of field names can eliminate each instance’s normal __dict__, depending on inheritance.
- Dataclasses support slots=True for a convenient generated implementation.