Python __init_subclass__() Magic Method

Rate this post

The Python class.__init_subclass__(cls) method is called on a given class each time a subclass cls for that class is created.

Syntax

class.__init_subclass__(cls)

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Minimal Example

The following example shows how as soon as you create a subclass Child that inherits from a Parent class, the method __init_subclass__() is called.

class Parent:
    def __init_subclass__(cls):
        print('Subclass of Parent Created!')

class Child(Parent):
    pass

Output:

Subclass of Parent Created!

💡 Note: The method is called on the definition of the class and not on the creation of an instance of the class. For example, even if you created 1000 instances of Child, the method __init_subclass__() would be called only once on Parent.

Class Hierarchy with __init_subclass__()

What happens if a child of a child class is created—does it trigger another execution of __init_subclass__()?

The answer is yes!

class Parent:
    def __init_subclass__(cls):
        print('Subclass of Parent Created!')

class Child(Parent):
    pass

class Grandchild(Child):
    pass

Output:

Subclass of Parent Created!
Subclass of Parent Created!

Precedence of Defining __init_subclass__() on Multiple Inheritance Levels

If both a class and a subclass define the __init_subclass__() method and a subclass of the subclass is created. Which __init_subclass__() definition applies in this scenario?

The normal subclass hierarchy rules apply: The closest parent class wins! Python goes from children to parents searching for __init_subclass__(). The first occurrence of the method is called.

class Parent:
    def __init_subclass__(cls):
        print('AAA')

class Child(Parent):
    def __init_subclass__(cls):
        print('BBB')

class Grandchild(Child):
    pass

Output:

AAA  # --> Output of Child()
BBB  # --> Output of Grandchild()

Background Inheritance

Inheritance allows you to define a class that inherits all methods and properties from another class.

  • Parent class, also denoted as base class, is the class you inherit from. In Python, every class can be a parent class.
  • Child class, also denoted as derived class, inherits from the Parent class. In Python, you can create a child class that inherits all methods and attributes from the Parent using the class Child(Parent) syntax with the parent class enclosed in parentheses.

You can watch our related video on inheritance here:

Five Types of Inheritance in Python

Learn more in our detailed articles: