What does the following code output, and what pattern does it demonstrate? class Registry: _registry = {} def __init_subclass__(cls, key=None, **kwargs): super().__init_subclass__(**kwargs) if key: Registry._registry[key] = cls class Dog(Registry, key=’dog’): pass class Cat(Registry, key=’cat’): pass print(Registry._registry)

Python Professional Hard

Python Professional — Hard

What does the following code output, and what pattern does it demonstrate? class Registry: _registry = {} def __init_subclass__(cls, key=None, **kwargs): super().__init_subclass__(**kwargs) if key: Registry._registry[key] = cls class Dog(Registry, key=’dog’): pass class Cat(Registry, key=’cat’): pass print(Registry._registry)

Key points

  • Subclasses are registered in the _registry dictionary with keys.
  • The __init_subclass__ method is used to add subclasses to the registry.
  • The correct output shows the keys and corresponding classes in the _registry dictionary.

Ready to go further?

Related questions