【Python】Python中的多行注释文档编写风格汇总

本文介绍了Python中的docstring概念及其重要性,并对比了几种不同的docstring风格,包括Epytext、Google、Numpydoc等,帮助开发者更好地理解如何撰写有效的代码文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【笔记】

Epytext风格比较紧凑(推荐);

Google风格和numpy风格层次分明,但是比较长;

================================

什么是docstring

在软件工程中,其实编码所占的部分是非常小的,大多是其它的事情,比如写文档。文档是沟通的工具。 
在Python中,比较推崇在代码中写文档,代码即文档,比较方便,容易维护,直观,一致。 
代码写完,文档也出来了。其实Markdown也差不多这种思想,文本写完,排版也完成了。 
看看PEP 0257中对docstring的定义:

A docstring is a string literal that occurs as the first statement in 
a module, function, class, or method definition. Such a docstring 
becomes the __doc__ special attribute of that object.
简单来说,就是出现在模块、函数、类、方法里第一个语句的,就是docstring。会自动变成属性__doc__。

?
1
2
def foo():
   """ This is function foo"""

可通过foo.__doc__访问得到' This is function foo'.

各类docstring风格:

Epytext

这是曾经比较流行的一直类似于javadoc的风格。

?
1
2
3
4
5
6
7
8
"""
This is a javadoc style.
 
@param param1: this is a first param
@param param2: this is a second param
@return: this is a description of what is returned
@raise keyError: raises an exception
"""

reST

这是现在流行的一种风格,reST风格,Sphinx的御用格式。我个人也是喜欢用这种风格,比较紧凑。

?
1
2
3
4
5
6
7
8
"""
This is a reST style.
 
:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""

Google风格

?
1
2
3
4
5
6
7
8
9
10
11
12
13
"""
This is a groups style docs.
 
Parameters:
   param1 - this is the first param
   param2 - this is a second param
 
Returns:
   This is a description of what is returned
 
Raises:
   KeyError - raises an exception
"""

Numpydoc (Numpy风格)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.
 
Parameters
----------
first : array_like
   the 1st param name `first`
second :
   the 2nd param
third : {'value', 'other'}, optional
   the 3rd param, by default 'value'
 
Returns
-------
string
   a value in a string
 
Raises
------
KeyError
   when a key error
OtherError
   when an other error
"""

docstring工具之第三方库pyment

用来创建和转换docstring. 
使用方法就是用pyment生成一个patch,然后打patch。

?
1
2
$ pyment test .py      #生成patch
$ patch -p1 < test .py.patch #打patch

详情:https://github.com/dadadel/pyment

使用sphinx的autodoc自动从docstring生产api文档,不用再手写一遍


转自:http://www.jb51.net/article/86757.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值