一、代码注释介绍
注释就是对代码的解释和说明,其目的是让人们能够更加轻松地了解代码。注释是编写程序时,写程序的人给一个语句、程序段、函数等的解释或提示,能提高程序代码的可读性。在有处理逻辑的代码中,源程序有效注释量必须在20%以上。
相关学习推荐: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 + num2print( 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 paramreturns: this is a description of what is returnedraises: keyerror - raises an exception"""
5.3 numpydoc (numpy风格)
"""my numpydoc description of a kindof very exhautive numpydoc format docstring.parameters----------first : array_like the 1st param name `first`second : the 2nd paramthird : {'value', 'other'}, optional the 3rd param, by default 'value'returns-------string a value in a stringraises------keyerror when a key errorothererror when an other error"""
六、一些注释经验
注释不是越多越好。对于一目了然的代码,不需要添加注释。对于复杂的操作,应该在操作开始前写上相应的注释。对于不是一目了然的代码,应该在代码之后添加注释。绝对不要描述代码。一般阅读代码的人都了解python的语法,只是不知道代码要干什么相关学习推荐:编程视频
以上就是解析python代码注释规范代码的详细内容。