1. 定义
摘自官方文档:docstring
A string literal which appears as the first expression in a class, function or module.
While ignored when the suite is executed, it is recognized by the compiler and put into the
__doc__ attribute of the enclosing class, function or module. Since it is available via
introspection, it is the canonical place for documentation of the object.
2. 示例代码(the_docstring.py)
#!/usr/bin/env python
"""Foo module used to learn docstring.
Author: the_author_name
Date: the_date
Other detail info about this module.
"""
import os
def foo():
'foo() docstring'
pass
def foo2():
"""foo2() docstring"""
pass
def foo3():
'foo3() docstring: first line.\nsecond line.'
pass
def foo4():
"""foo4() docstring: first line.
second line."""
pass
class Foo(object):
"class Foo's docstring."
def foo():
"""Foo.foo() docstring: first line.
second line."""
pass
3. 运行结果
<pre name="code" class="plain">D:\examples\python\docstring>python -m pydoc the_docstring
Help on module the_docstring:
NAME
the_docstring - Foo module used to learn docstring.
FILE
d:\examples\python\docstring\the_docstring.py
DESCRIPTION
Author: the_author_name
Date: the_date
Other detail info about this module.
CLASSES
__builtin__.object
Foo
class Foo(__builtin__.object)
| class Foo's docstring.
|
| Methods defined here:
|
| foo()
| Foo.foo() docstring: first line.
| second line.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
FUNCTIONS
foo()
foo() docstring
foo2()
foo2() docstring
foo3()
foo3() docstring: first line.
second line.
foo4()
foo4() docstring: first line.
second line.
D:\examples\python\docstring>
4. 说明
如同本文开始所提到的,docstring是一个函数或类开头的第一个literal string。如果这个字符串有多行,为了避免使用\n的语法,通常使用一对'''或"""表示的字符串。
模块的docstring必须写在整个python文件的最开始的地方,或第一条python expression之前。如同示例代码表示的,#!/usr/bin/env python可以是第一条语句(对于Linux环境而言通常都是必须的),因为这句话是Python的注释部分。对于import语句,则必须定义在docstring的后面。
即便自己的代码,添加docstring也是有好处的。这个时候不用打开源代码文件,直接通过命令即可查询特定函数或类的帮助信息。