Auto-register class methods using decorator

前端 未结 7 914
粉色の甜心
粉色の甜心 2020-12-05 00:46

I want to be able to create a python decorator that automatically \"registers\" class methods in a global repository (with some properties).

Example code:

         


        
相关标签:
7条回答
  • 2020-12-05 01:39

    Not easy, but if you are using Python 3 this should work:

    registry = {}
    
    class MetaRegistry(type):
    
        @classmethod
        def __prepare__(mcl, name, bases):
            def register(*props):
                def deco(f):
                    registry[name + "." + f.__name__] = props
                    return f
                return deco
            d = dict()
            d['register'] = register
            return d
    
        def __new__(mcl, name, bases, dct):
            del dct['register']
            cls = super().__new__(mcl, name, bases, dct)
            return cls
    
    class my_class(object, metaclass=MetaRegistry):
    
        @register('prop1','prop2')
        def my_method( arg1,arg2 ):
           pass # method code here...
    
        @register('prop3','prop4')
        def my_other_method( arg1,arg2 ):
           pass # method code here...
    
    print(registry)
    

    Note that you can not have method names equal to the decorator name in the meta-typed class, because they are automatically deleted by the del command in the metaclass's __new__ method.

    For Python 2.6 I think you would have to explicitly tell the decorator the class name to use.

    0 讨论(0)
提交回复
热议问题