🐍 Python Advanced

What is Python's __init_subclass__ and class decorators?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

Answer

__init_subclass__(cls, **kwargs) is a class method called when the class is subclassed, allowing the parent to hook into subclass creation without a metaclass. Example (plugin registry): class Plugin: registry = {}; def __init_subclass__(cls, name="", **kwargs): super().__init_subclass__(**kwargs); if name: Plugin.registry[name] = cls. Subclass: class LogPlugin(Plugin, name="log") — automatically registered. Class decorators are simpler than metaclasses for modifying classes: def add_repr(cls): cls.__repr__ = lambda self: f"{cls.__name__}({vars(self)})" return cls; @add_repr class MyClass: .... Choose: metaclasses for deep class creation control, __init_subclass__ for subclass registration/notification, class decorators for adding/modifying attributes after creation. __init_subclass__ is the modern, simpler alternative to metaclass hooks for most use cases.

Pro Tip

This topic has Python-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.