In Python, the __init_subclass__()
method is a powerful and lesser-known tool for customizing class creation behavior in subclasses.
Example:
class Plugin:
plugins = []
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.plugins.append(cls)
class ConcretePlugin(Plugin):
pass
class AnotherPlugin(Plugin):
pass
print(Plugin.plugins)
# Output: [<class '__main__.ConcretePlugin'>, <class '__main__.AnotherPlugin'>]
📘 Plugin is a base class.
🚀 Whenever a subclass of Plugin is defined, init_subclass of Plugin is automatically called.
🔍 Inside the init_subclass method, the newly defined subclass (cls in this context) is appended to the plugins list.
✅ So, after defining the ConcretePlugin and AnotherPlugin subclasses, the plugins list contains references to these two classes.
This technique can be useful to enforce certain constraints, add class-level attributes, or perform any setup tasks 💡 💪
This feature was introduced in #Python 3.6 - PEP 487 – Simpler customisation of class creation 😎
#classes #oop