python常用注释风格-Google
一、高层概览
python的注释规范有哪些?
主要有PEP8 规范,PEP 257,以及Google的注释风格。
PEP8是官方的、基础性的规范(略略略)。
PEP257是Python Enhancement Proposal(增强规范)的一部分,专门针对文档字符串
有哪些主要的注释位置?
- python文件头
- 类的文档字符串(docstrings)
- 函数和方法的docstrings
为什么选择Google注释风格?
简洁!清晰!易读!
二、最佳实例 - Google风格
1.函数和方法的注释
def function_name(param1, param2):
"""Function summary line. (简单描述该函数或方法的功能)
Args:
param1 (int): The first parameter.
param2 (str): The second parameter.
Returns:
bool: The return value. True for success, False otherwise.
Raises: (这里提供了可能会碰到的报错,非必要可不写)
ValueError: If `param1` is equal to `param2`.
"""
# 注意通过空行增加可读性
2.类的注释
类的注释主要描述类的功能和属性(Attributes)。注意,**‘__init__’**中的相关内容(如参数)应该在类的docstrings中体现。
class SampleClass:
"""Summary of class here.
Longer class information....
Longer class information....
Attributes:
likes_spam (bool): A boolean indicating if we like SPAM or not.
eggs (int): The number of eggs we have.
"""
def __init__(self, likes_spam=False):
"""Inits SampleClass with blah."""
self.likes_spam = likes_spam
self.eggs = 0
3.模块注释
"""A one-line summary of the module. (简单的概述模块)
A longer description of the module.(模块的细节)
"""
import sys
# 注意通过空行增加可读性
4.块注释和行注释
对块注释和行注释也进行了差异化:
块注释解释整块的,没那么一目了然的代码:
"""
This is a block comment
that spans multiple lines
"""
行注释用来解释单行,不要过多的使用:
# This is a line comment