Prerequisites: Python Classes and Objects, Inheritance 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__
__init_subclass__
# defining a SuperClass class SuperClass:        # defining __init_subclass__ method     def __init_subclass__(cls, **kwargs):         cls.default_name ="Inherited Class"  # defining a SubClass class SubClass(SuperClass):        # an attribute of SubClass     default_name ="SubClass"     print(default_name)   subclass = SubClass() print(subclass.default_name) |
Output :
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).
This __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.
Example:
# defining a SuperClass class SuperClass:     def __init_subclass__(cls, default_name, **kwargs):         cls.default_name = default_name   # defining a subclass class SubClass1(SuperClass, default_name ="SubClass1"):     pass  # defining another subclass class SubClass2(SuperClass, default_name ="SubClass2"):     default_name = "InheritedClass"    # references for subclasses subClass1 = SubClass1() subClass2 = SubClass2()   print(subClass1.default_name) print(subClass2.default_name) |
Output :
SubClass1 SubClass2
By this we can conclude that __init_subclass__ method is used to alter the behavior of subclasses which may be created in future.

… [Trackback]
[…] Read More Information here on that Topic: geeksforgeeks.org/init-subclass-in-python/ […]