2016-01-06 27 views
2

有沒有辦法用inspect模塊以編程方式查找所有@property裝飾方法的名稱?使用檢查模塊查找@property方法

+0

這似乎是第一個同類問題? http://stackoverflow.com/search?q=%40cached_property+inspect –

+0

我已經搜遍了網絡和文檔,我沒有看到辦法做到這一點。 –

+0

我打賭@AlexMartelli將獲得第一個職位。 –

回答

2

我的版本:

import inspect 


class A(object): 
    @property 
    def name(): 
     return "Masnun" 


def method_with_property(klass): 
    props = [] 

    for x in inspect.getmembers(klass): 

     if isinstance(x[1], property): 
      props.append(x[0]) 

    return props 

print method_with_property(A) 

從另一個線程另一個版本:

import inspect 

def methodsWithDecorator(cls, decoratorName): 
    sourcelines = inspect.getsourcelines(cls)[0] 
    for i,line in enumerate(sourcelines): 
     line = line.strip() 
     if line.split('(')[0].strip() == '@'+decoratorName: # leaving a bit out 
      nextLine = sourcelines[i+1] 
      name = nextLine.split('def')[1].split('(')[0].strip() 
      yield(name) 

class A(object): 
    @property 
    def name(): 
     return "Masnun" 



print list(methodsWithDecorator(A, 'property')) 

methodsWithDecorator的代碼是從公認的答案就這項主題:Howto get all methods of a python class with given decorator