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

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

    I don't want to add much, just a simple variation of ninjagecko's Method 2. It works wonders.

    Same code, but using list comprehension instead of a generator, which is what I needed.

    def methodsWithDecorator(cls, decoratorName):
    
        sourcelines = inspect.getsourcelines(cls)[0]
        return [ sourcelines[i+1].split('def')[1].split('(')[0].strip()
                        for i, line in enumerate(sourcelines)
                        if line.split('(')[0].strip() == '@'+decoratorName]
    

提交回复
热议问题