2012-09-05 22 views
0

如何獲得一個包含班級所有功能但不按字母順序排列的列表? 因爲實際上我有一個: 按書寫順序列出班級的所有功能

[ foo.__dict__.get(a) for a in dir(foo) if isinstance(foo.__dict__.get(a), types.FunctionType) ] 

,並返回我一個名單,但重新排序... 我也試着與裝飾:

def decorator(): 
    listing = [] 
    def wrapped (func): 
     listing.append(func) 
     return func 
    wrapped.listing = listing 
    return wrapped 

這很好,但我需要在我班的每個功能上添加一個裝飾器...可能是你有一些技巧?

+0

'字典不保存順序。所以如果你想按照外觀順序,你可能需要使用正則表達式進行解析。 – tuxuday

回答

6

請參閱inspect模塊文檔。函數對象具有func_code屬性,並且(根據文檔 - 尚未對其進行測試),func_code應具有co_firstlineno屬性,這將是源文件中第一行代碼的編號。

所以請儘量類似:

def getListOfClassFunctions(foo): 
    '''foo - a class object''' 
    funcList = [ foo.__dict__.get(a) for a in dir(foo) if isinstance(foo.__dict__.get(a), types.FunctionType)] 
    funcList = filter(lambda x: x.func_code.co_filename == foo.__module__, funcList) # Thanks Martijn Pieters for a hint! 
    return sorted(key=lambda x: x.func_code.co_firstlineno, funcList) 

編輯來包裝整個片段中的功能,並僅返回相同的模塊類定義的功能。

+1

這實際上非常聰明,只要所有函數已經在同一個類體中定義了(稍後不會被閂上),它就會工作。 –

+0

@MartijnPieters:是的,我知道動態添加的函數在這裏不會很好用。但是,通過文件中的位置排序所有函數的任務並沒有很好地定義爲動態添加的函數:) – Abgan

+1

是的,我完全同意,只是指出了一點小細節。你可以使用'.co_filename'來保持各種功能的不同,並提供至少一個穩定的順序,使* some *有意義。 :-)我知道,Edgecase仍然欣賞這個想法。 –