__init_subclass__ in Python
Regardless of any programming languages, Inheritance is one of the most important topics in Object-Oriented Programming Concepts. Inheritance is a concept of defining a class in terms of another class. As per inheritance, we know that a superclass reference can hold its subclass reference. We all know that the behavior of the superclass can be altered according to the implementation of its sub-class(es).
But now, we can alter the behavior of the sub-class(es) by using __init_subclass__
SubClass Inherited Class
Understanding the code
- In the above example, there are 2 classes(i.e Super Class and SubClass) and SubClass is inherited from SuperClass. default_name is an attribute of SubClass.
- The value of attribute default_name is altered by SuperClass by using __init_subclass__ method.
- cls is referred to the subclass(es) which are inherited. Keyword arguments(**kwargs) which are given to a new class are passed to the parent’s class __init_subclass__.
- For compatibility with other subclasses using __init_subclass__, one should take out the needed keyword arguments and pass the others over to the base class(Super Class).
__init_subclass__ closely look alike Decorator class. But where class decorators only affect the specific class they are applied to,
__init_subclass__ solely applies to future sub-classes of the class defining the method. It means we can alter/define the behavior of any new classes which are inherited from super-class.
By this we can conclude that __init_subclass__ method is used to alter the behavior of subclasses which may be created in future.