How to get all methods of a python class with given decorator

后端 未结 6 1967
天命终不由人
天命终不由人 2020-12-02 05:18

How to get all methods of a given class A that are decorated with the @decorator2?

class A():
    def method_a(self):
      pass

    @decorator1
    def met         


        
6条回答
  •  北海茫月
    2020-12-02 06:04

    If you do have control over the decorators, you can use decorator classes rather than functions:

    class awesome(object):
        def __init__(self, method):
            self._method = method
        def __call__(self, obj, *args, **kwargs):
            return self._method(obj, *args, **kwargs)
        @classmethod
        def methods(cls, subject):
            def g():
                for name in dir(subject):
                    method = getattr(subject, name)
                    if isinstance(method, awesome):
                        yield name, method
            return {name: method for name,method in g()}
    
    class Robot(object):
       @awesome
       def think(self):
          return 0
    
       @awesome
       def walk(self):
          return 0
    
       def irritate(self, other):
          return 0
    
    

    and if I call awesome.methods(Robot) it returns

    {'think': , 'walk': }
    

提交回复
热议问题