docstring

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也是有好处的。这个时候不用打开源代码文件,直接通过命令即可查询特定函数或类的帮助信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值