为什么需要写好注释?
软件开发过程,写好注释,可以让代码更清晰,更容易维护,也能令他人更容易理解自己写的代码,提高团队效率。
Python还有1个功能,可以用 pydoc模块根据docstrings 注释生成软件说明书。
python 注释类型
python语法中,有两种注释
- 用 # 号开头的注释,
# comment
, 是单行注释 - 用 3个双引号或单引号括起来的注释,
”“” comment “”“
, 通常是多行,也可以是单行,注:后面统一用”多行注释“来代表3个引号注释
单行注释
1、使用语法:
#COMMENT
CODE #COMMENT
注释用中文、英文都可以。
2、什么地方使用单行注释?
1) 复杂的代码块前加注释,简要说明该代码块的功能
# iterates over name list and prints each name
for student in names:
print(student, end=' ')
2) 代码同一行加注释
注意要短
y_onehot = np.zeros((y_train.shape[0], 2)) # one-hot 编码
3) 文件头说明
#----------------------------------------------------------------
# filename: abc.py |
# Description: calculate spent time in seconds for a function |
# Author: Zhang Fei, updated on 2022-7-20 |
#----------------------------------------------------------------
- 开发过程中,提示代码变更
在已有代码中添加新功能,适当注明变更,可以提高效率
# temp branch 1.04.a, updated by Zhang Fei on 2022-7-20
代码验证测试,正式提交前,可以删除该类注释
要避免的事
- 给很容易看懂的代码前加注释
- 含义重复的注释
- 注释用语不准确,他人不能理解
多行注释
用 “”" “”" 来写的注释,可以多行,也可以单行。 也是类或方法的__doc__
属性的值, 因此也称也称为 docstring 注释。
python可使用pydoc模块,根据doctring注释,自动生成程序说明文档.
1. 添加位置
docstring注释应该放在 类, 函数代码的第1行
2. 单行 docstring 注释
简单地说明函数功能,及返回值
def multiplier(a, b):
"""Takes in two numbers, returns their product."""
return a*b
3. 多行 docstring 注释
函数注释示例 :
Google 风格中的注释,分为 4部分 (1) 功能简介 (2) args (3) return (4)raise 异常
"""
This is an example of Google style.
Args:
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.
"""
示例1:
def add_binary(a, b):
'''
Returns the sum of two decimal numbers in binary digits.
Args:
a (int): A decimal integer
b (int): Another decimal integer
Returns:
binary_sum (str): Binary string of the sum of a and b
Raises:
keyerror: Raises an exception.
'''
try:
binary_sum = bin(a+b)[2:]
except keyerror as e:
print(e)
return binary_sum
# 检查打印效果
print(add_binary.__doc__)
class 注释示例 :
3部分: (1) 类的主要作用 (2) Attributes (3) Methods
class Person:
"""
A class to represent a person.
Attributes
----------
name : str
first name of the person
surname : str
family name of the person
age : int
age of the person
Methods
-------
info(additional=""):
Prints the person's name and age.
"""
def info(self, additional=""):
"""
Prints the person's name and age.
If the argument 'additional' is passed, then it is appended after the main info.
args
----------
additional : str, optional
More info to be displayed (default is None)
Returns
-------
None
"""
print(f'My name is {self.name} {self.surname}. I am {self.age}
检查 docstrings 注释打印效果
print(Person.__doc__)
希望本文对您有所帮助,谢谢阅读!