MOb*_*ect 0 python class function list
如何列出包含类的所有功能但不按字母顺序重新排序的列表?因为实际上我有:
[ foo.__dict__.get(a) for a in dir(foo) if isinstance(foo.__dict__.get(a), types.FunctionType) ]
Run Code Online (Sandbox Code Playgroud)
它返回给我一个列表但重新排序...我也尝试过一个装饰者:
def decorator ():
listing = []
def wrapped (func):
listing.append(func)
return func
wrapped.listing = listing
return wrapped
Run Code Online (Sandbox Code Playgroud)
那很好但是,我需要在我班级的每个功能上添加一个装饰器......可能你有一些技巧?
请参阅检查模块文档.函数对象有 func_codeattr,并且(根据文档 - 尚未测试它),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)
Run Code Online (Sandbox Code Playgroud)
编辑以将整个片段包装在函数中,并仅返回与类在同一模块中定义的函数.