The __init_subclass__
is an addition to Python 3.6 to reduce the need for custom metaclasses, as many of its uses are "overkill".
The idea is that each subclass that is created for a (normal, non-meta) base-class that contains an __init_subclass__
method, it willbe called, with the new subclass as first parameter:
class Base:
def __init_subclass__(subclass, debug=None, typecheck=None, **kwargs):
# do stuff with the optional debug and typecheck arguments
# Pass possible arguments not consumed here to superclasses, if any:
super().__init_subclass__(**kwargs)
And there is no need for a metaclass at all - the __prepare__
, __init__
and __new__
of the default metaclass - type
- will ignore any named argument passed in this way. But the default __init_subclass__
in object will raise if unknown named arguments reach it - the pattern above will consume these arguments, removing them from kwargs. If you are dealing with unknown named arguments, just process kwargs like a normal dictionary - no need for explicit named parameters in the __init_subclass__
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…