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

后端 未结 6 1971
天命终不由人
天命终不由人 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 05:46

    Maybe, if the decorators are not too complex (but I don't know if there is a less hacky way).

    def decorator1(f):
        def new_f():
            print "Entering decorator1", f.__name__
            f()
        new_f.__name__ = f.__name__
        return new_f
    
    def decorator2(f):
        def new_f():
            print "Entering decorator2", f.__name__
            f()
        new_f.__name__ = f.__name__
        return new_f
    
    
    class A():
        def method_a(self):
          pass
    
        @decorator1
        def method_b(self, b):
          pass
    
        @decorator2
        def method_c(self, t=5):
          pass
    
    print A.method_a.im_func.func_code.co_firstlineno
    print A.method_b.im_func.func_code.co_firstlineno
    print A.method_c.im_func.func_code.co_firstlineno
    

提交回复
热议问题