__slots__ — Intermediate Playground
Restricts instance attributes to a fixed set for memory savings
Python Playground
# Using __slots__ with custom classes
class Registry:
def __init__(self):
self._items = {}
def register(self, cls):
self._items[cls.__name__] = cls
return cls
def get(self, name):
return self._items.get(name)
registry = Registry()
@registry.register
class Widget:
pass
@registry.register
class Button:
pass
print(registry._items)
print(registry.get("Widget"))
Output
Click "Run" to execute your code
Custom classes interact with __slots__ in specific ways that are useful to understand.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?