2009-08-13 87 views

回答

7

任何文檔字符串可以通過.__doc__屬性:

>>> print str.__doc__ 

在Python 3,你需要括號打印:

>>> print(str.__doc__) 
3

您可以使用dir( {插入類的名字在這裏} )獲取一個類的內容,然後遍歷它,尋找方法或其他東西。這個例子看起來一類Task啓動名爲cmd方法,並得到他們的文檔字符串:

command_help = dict() 

for key in dir(Task): 
    if key.startswith('cmd'): 
     command_help[ key ] = getattr(Task, key).__doc__ 
1

.__doc__是最好的選擇。但是,您也可以使用inspect.getdoc獲取docstring。使用它的一個優點是,它可以從縮排排列代碼塊的文檔字符串中刪除縮進。

實施例:

In [21]: def foo(): 
    ....:  """ 
    ....:  This is the most useful docstring. 
    ....:  """ 
    ....:  pass 
    ....: 

In [22]: from inspect import getdoc 

In [23]: print(getdoc(foo)) 
This is the most useful docstring. 

In [24]: print(getdoc(str)) 
str(object='') -> string 

Return a nice string representation of the object. 
If the argument is a string, the return value is the same object.