python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python代码注释

Python代码注释规范代码实例解析

作者:蓝 寅

这篇文章主要介绍了Python代码注释规范代码实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

一、代码注释介绍

二、代码注释分类

行注释:在符号后那一行不会被编译(显示)

块注释:被块注释符号中间的部分不会被编译

三、python代码注释基础

Python中使用#表示单行注释。单行注释可以作为单独的一行放在被注释代码行之上,也可以放在语句或表达式之后。如下例子:

name = 'xiaohong' # 单行注释

# 单行注释
name = 'xiaohong'

Python中使用三个单引号或三个双引号表示多行注释。用在注释多写不下的情况,如下例子:

'''
这是使用三个单引号的多行注释
'''

"""
这是使用三个双引号的多行注释
"""

四、DocStrings介绍与使用

4.1 DocStrings介绍

文档字符串

是一个重要工具,用于解释文档程序,帮助你的程序文档更加简单易懂

4.2 python中使用DocStrings

在函数体的第一行使用一对三个单引号 ''' 或者一对三个双引号 """ 来定义文档字符串。你可以使用 doc(注意双下划线)调用函数中的文档字符串属性。

编写示例如下:

def add(num1,num2):
  """ 完成传入的两个数之和

  :param num1: 加数1
  :param num2: 加数2
  :return: 和
  """
  return num1 + num2

print( add.__doc__ )

备注:DocStrings 文档字符串使用惯例:它的首行简述函数功能,第二行空行,第三行为函数的具体描述。

五、DocStrings常用编写风格

5.1 reST风格

这是现在流行的一种风格,reST风格,Sphinx的御用格式,比较紧凑。

"""
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
"""

5.2 Google风格

"""
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
"""

5.3 Numpydoc (Numpy风格)

"""
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
"""

六、一些注释经验

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文