2009-08-13 86 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.