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

来源:互联网 发布:棉柔巾 知乎 编辑:程序博客网 时间:2024/05/17 00:18

【笔记】

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

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 宜和书谱 笑忘书吉他谱 孙过庭书谱字帖高清 孙过庭书谱原文 书谱释文 孙过庭书谱下载 孙过庭书谱原文及译文 孙过庭书谱价格 唐孙过庭书谱 金书群芳谱 孙过庭书谱朗诵 孙过庭书谱字帖 搬杆子二神唱词书谱 书趣 书同文车同轨 混一车书 车同轨书同文什么意思 书车 竹制家具 书轩 迂怎么读 迂拼音 迂的拼音 迂的意思 迂谈阔论 主动脉迂曲 迂组词 迂阔 输卵管迂曲 出入之迂也的之 庶门风华千年书一桐 千年书一桐 庶门风华 庶门风华 千年书一桐 中华玄门 群书 六一书阁 书阁 望书阁 圣书阁 帝书阁 烧书阁