object .__ init_subclass __ (cls)
-> None
cls - The inherited class to be initialized.
Called whenever there is inheritance from the class in which this method is defined.
Using the method simplifies the execution of some types of tasks that were previously solved using metaclasses.
Note
The default method implementation does nothing. However, it raises TypeError if arguments are passed to it.
class Base:
"" "Base class that handles initialization of inheritors." ""
registry = []
def __init_subclass __ (cls, my_arg = ’some’):
super () .__ init_subclass __ ()
# For example, create a registry of all descendants.
cls.registry.append (cls)
# Output the argument.
print (my_arg)
class Child1 (Base):
"" "The first class is the descendant." ""
class Child2 (Base, my_arg = ’two’):
" "" Second successor. Pay attention to the possibility of passing an argument to the initializer using the example of my_arg.
"" "
class SubChild1 (Child1, my_arg = ’sub’):
" "" And a nested successor. "" "
# print in the initializer will output:
# some
# two
# sub
# And now let’s see what has accumulated in the register of heirs:
print (Base.registry)
# ["class ’__main __. Child1’ & gt ;, "class’ __main__ .Child2’ & gt ;, "class ’__main __. SubChild1’"]
Note
Metaclasses are never passed into this method.