How to auto register a class when it's defined

后端 未结 6 475
无人及你
无人及你 2020-12-04 19:23

I want to have an instance of class registered when the class is defined. Ideally the code below would do the trick.

registry = {}

def register( cls ):
            


        
6条回答
  •  误落风尘
    2020-12-04 19:50

    Since python 3.6 you don't need metaclasses to solve this

    In python 3.6 simpler customization of class creation was introduced (PEP 487).

    An __init_subclass__ hook that initializes all subclasses of a given class.

    Proposal includes following example of subclass registration

    class PluginBase:
        subclasses = []
    
        def __init_subclass__(cls, **kwargs):
            super().__init_subclass__(**kwargs)
            cls.subclasses.append(cls)
    

    In this example, PluginBase.subclasses will contain a plain list of all subclasses in the entire inheritance tree. One should note that this also works nicely as a mixin class.

提交回复
热议问题