Auto-register class methods using decorator

前端 未结 7 916
粉色の甜心
粉色の甜心 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:28

    If you need the classes name, use Matt's solution. However, if you're ok with just having the methods name -- or a reference to the method -- in the registry, this might be a simpler way of doing it:

    class Registry:
        r = {}
    
        @classmethod
        def register(cls, *args):
            def decorator(fn):
                cls.r[fn.__name__] = args
                return fn
            return decorator
    
    class MyClass(object):
    
        @Registry.register("prop1","prop2")
        def my_method( arg1,arg2 ):
            pass
    
        @Registry.register("prop3","prop4")
        def my_other_method( arg1,arg2 ):
            pass
    
    print Registry.r
    

    print

    {'my_other_method': ('prop3', 'prop4'), 'my_method': ('prop1', 'prop2')}
    

提交回复
热议问题