【发布时间】:2010-11-19 05:29:04
【问题描述】:
我想在我的命令行应用程序中获取文档字符串,但是每次我调用内置的 help() 函数时,Python 都会进入交互模式。
如何获取对象的文档字符串并且没有让 Python 获取焦点?
【问题讨论】:
标签: python interactive
我想在我的命令行应用程序中获取文档字符串,但是每次我调用内置的 help() 函数时,Python 都会进入交互模式。
如何获取对象的文档字符串并且没有让 Python 获取焦点?
【问题讨论】:
标签: python interactive
.__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.
【讨论】:
您可以使用dir({在此处插入类名}) 获取类的内容,然后对其进行迭代,查找方法或其他内容。此示例在类 Task 中查找以名称 cmd 开头的方法并获取它们的文档字符串:
command_help = dict()
for key in dir( Task ):
if key.startswith( 'cmd' ):
command_help[ key ] = getattr( Task, key ).__doc__
【讨论】:
任何文档字符串都可以通过.__doc__ 属性获得:
>>> print str.__doc__
在 python 3 中,您需要括号来打印:
>>> print(str.__doc__)
【讨论】: