Understanding __init_subclass__

后端 未结 4 1577
甜味超标
甜味超标 2020-12-23 09:44

I finally upgraded my python version and I was discovering the new features added. Among other things, I was scratching my head around the new __init_subclass__ method. From

4条回答
  •  太阳男子
    2020-12-23 10:05

    The main point of __init_subclass__ was, as the title of the PEP suggest, to offer a simpler form of customization for classes.

    It's a hook that allows you to tinker with classes w/o the need to know about metaclasses, keep track of all aspects of class construction or worry about metaclass conflicts down the line. As a message by Nick Coghlan on the early phase of this PEP states:

    The main intended readability/maintainability benefit is from the perspective of more clearly distinguishing the "customises subclass initialisation" case from the "customises runtime behaviour of subclasses" case.

    A full custom metaclass doesn't provide any indication of the scope of impact, while __init_subclass__ more clearly indicates that there's no persistent effects on behaviour post-subclass creation.

    Metaclasses are considered magic for a reason, you don't know what their effects will be after the class will be created. __init_subclass__, on the other hand, is just another class method, it runs once and then it's done. (see its documentation for exact functionality.)


    The whole point of PEP 487 is about simplifying (i.e removing the need to use) metaclasses for some common uses.

    __init_subclass__ takes care of post-class initialization while __set_name__ (which makes sense only for descriptor classes) was added to simplify initializing descriptors. Beyond that, they aren't related.

    The third common case for metaclasses (keeping definition order) which is mentioned, was also simplified. This was addressed w/o a hook, by using an ordered mapping for the namespace (which in Python 3.6 is a dict, but that's an implementation detail :-)

提交回复
热议问题