__slots__ — Easy Examples
Restricts instance attributes to a fixed set for memory savings
Accessing __slots__
How to access and use __slots__.
python
# __slots__ restricts attribute creation for memory efficiency class Point: __slots__ = ("x", "y") def __init__(self, x, y): self.x = x self.y = y p = Point(1, 2) print(p.x, p.y) try: p.z = 3 except AttributeError as e: print(f"Cannot add: {e}")
__slots__ is a special attribute that restricts instance attributes to a fixed set for memory savings.
__slots__ in practice
Using __slots__ in everyday code.
python
# More __slots__ examples print("__slots__ is a special Python attribute") # Every object has certain dunder attributes obj = object() attrs = [a for a in dir(obj) if a.startswith("__")] print(f"object has {len(attrs)} dunder attributes")
Understanding __slots__ helps you introspect and debug Python objects.
Want to try these examples interactively?
Open Easy Playground