Auto-register class methods using decorator

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

    Not as beautiful or elegant, but probably the simplest way if you only need this in one class only:

    _registry = {}
    class MyClass(object):
        def register(*prop):
            def decorator(meth):
                _registry[MyClass.__name__ + '.' + meth.__name__] = prop
            return decorator
    
        @register('prop1', 'prop2')
        def my_method(self, arg1, arg2):
            pass
        @register('prop3', 'prop4')
        def my_other_method(self, arg1, arg2):
            pass
    
        del register
    

提交回复
热议问题