刘刚刚的个人博客

python代码注释-看这一篇就可以

创建时间:2021-10-15 18:52:21
更新时间:2021-10-15 22:52:34

从注释方法到docstring,到注释规范,再使用工具来提高开发效率。

python中的注释方法

  1. 单行注释:使用#号进行注释

    # 单行注释 
  2. 多行注释:使用三个双引号或单引号来注释多行内容

    '''
    单引号进行多行注释
    '''
    
    """
    双引号进行多行注释
    """

docstring

docstring是Python中独一无二的的注释方式,为字符串形式,是包, 模块, 类或函数里的第一个语句。 这些字符串可以通过对象的 __doc__ 来获取。

from icecream import ic

# demo.py文件
def display(add):
    '''
    这是一个函数
    '''
    print(add)

# 这是一个注释在外边的函数    
def out(add):
    print(add)

class my_cla:
    '''
    这是一个类
    '''
    def say(self,add):
        '''
        这是一个类实例方法
        '''
        print(add)

ic(display.__doc__)
ic(out.__doc__)
ic(my_cla.__doc__)
ic(my_cla.say.__doc__)

>>>
ic| display.__doc__: '
                          这是一个函数
                          '
ic| out.__doc__: None
ic| my_cla.__doc__: '
                         这是一个类
                         '
ic| my_cla.say.__doc__: '
                                 这是一个类实例方法
                                 '

通过代码及输出,可以看到只有在函数中的第一个字符串才能被__doc__输出,即为docstring。

注释的规范

一个文档字符串应该这样组织:

  1. 首先是一行以句号, 问号或惊叹号结尾的概述(或者该文档字符串单纯只有一行).
  2. 接着是一个空行.
  3. 接着是文档字符串剩下的部分, 它应该与文档字符串的第一行的第一个引号对齐.

下边将介绍不同的注释场景中的注释方法。

模块

应该根据项目使用的许可(Appache2.0,GPL)来包行一个许可模板,开头(__init__.py文件中)应该是对模块内容和用法的概述。

示例:

"""A one line summary of the module or program, terminated by a period.

Leave one blank line.  The rest of this docstring should contain an
overall description of the module or program.  Optionally, it may also
contain a brief description of exported classes and functions and/or usage
examples.

Typical usage example:

foo = ClassFoo()
bar = foo.FunctionBar()
"""

函数(函数、方法、生成器)

一个函数必须要有文档字符串,除非满足以下条件:

  1. 外部不可见
  2. 非常短小
  3. 简单明了

文档字符串应该:

  1. 包含函数做什么,而不是怎么做的。
  2. 让使用者不需要看一行代码,只需要看文档就可以
  3. 包含输入和输出的详细描述
  4. 对于复杂的代码可以在代码旁边加注释
  5. 覆盖基类的方法可以加:See base class

在文档字符串中,应该根据不同的内容进行分组。文档字符串常用的分组:

  • Args:

    列出每个参数的名字, 并在名字后使用一个冒号和一个空格, 分隔对该参数的描述.如果描述太长超过了单行80字符,使用2或者4个空格的悬挂缩进(与文件其他部分保持一致). 描述应该包括所需的类型和含义. 如果一个函数接受foo(可变长度参数列表)或者*bar (任意关键字参数), 应该详细列出*foo**bar.

  • Returns: (或者 Yields: 用于生成器)

    描述返回值的类型和语义. 如果函数返回None, 这一部分可以省略.

  • Raises:

    列出与接口有关的所有异常.

示例1:

def fetch_smalltable_rows(table_handle: smalltable.Table,
                        keys: Sequence[Union[bytes, str]],
                        require_all_keys: bool = False,
) -> Mapping[bytes, Tuple[str]]:
    """Fetches rows from a Smalltable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by table_handle.  String keys will be UTF-8 encoded.

    Args:
        table_handle: An open smalltable.Table instance.
        keys: A sequence of strings representing the key of each table
        row to fetch.  String keys will be UTF-8 encoded.
        require_all_keys: Optional; If require_all_keys is True only
        rows with values set for all keys will be returned.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:

        {b'Serak': ('Rigel VII', 'Preparer'),
        b'Zim': ('Irk', 'Invader'),
        b'Lrrr': ('Omicron Persei 8', 'Emperor')}

        Returned keys are always bytes.  If a key from the keys argument is
        missing from the dictionary, then that row was not found in the
        table (and require_all_keys must have been False).

    Raises:
        IOError: An error occurred accessing the smalltable.
    """

示例2(在args中换行):

def fetch_smalltable_rows(table_handle: smalltable.Table,
                        keys: Sequence[Union[bytes, str]],
                        require_all_keys: bool = False,
) -> Mapping[bytes, Tuple[str]]:
    """Fetches rows from a Smalltable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by table_handle.  String keys will be UTF-8 encoded.

    Args:
    table_handle:
        An open smalltable.Table instance.
    keys:
        A sequence of strings representing the key of each table row to
        fetch.  String keys will be UTF-8 encoded.
    require_all_keys:
        Optional; If require_all_keys is True only rows with values set
        for all keys will be returned.

    Returns:
    A dict mapping keys to the corresponding table row data
    fetched. Each row is represented as a tuple of strings. For
    example:

    {b'Serak': ('Rigel VII', 'Preparer'),
    b'Zim': ('Irk', 'Invader'),
    b'Lrrr': ('Omicron Persei 8', 'Emperor')}

    Returned keys are always bytes.  If a key from the keys argument is
    missing from the dictionary, then that row was not found in the
    table (and require_all_keys must have been False).

    Raises:
    IOError: An error occurred accessing the smalltable.
    """

类应该在其定义下有一个用于描述该类的文档字符串. 如果有公共属性(Attributes), 那么文档中应该有一个属性(Attributes)段. 并且应该和函数参数的格式相同。

class SampleClass(object):
    """Summary of class here.

    Longer class information....
    Longer class information....

    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """

    def __init__(self, likes_spam=False):
        """Inits SampleClass with blah."""
        self.likes_spam = likes_spam
        self.eggs = 0

    def public_method(self):
        """Performs operation blah."""

块注释和行注释

如果代码在代码审查的时候,可能需要再次思索该代码意义,那么就应该写注释。

需要注意以下两点:

  1. 行注释,应离开代码最少两个空格。
  2. 不要描述代码,阅读代码的时候,一般不是看不懂,而不是不认识。

示例:

# We use a weighted dictionary search to find out where i is in
# the array.  We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.

if i & (i-1) == 0:        # True if i is 0 or a power of 2.

pydoc、sphinx的使用方法(待补充)

推荐使用sphinx

需处理问题:

  • 注解与pydoc
  • 函数上边的注释能否显示到pydoc中

pycharm注释设置方法

创建文件时自动添加注释

设置的位置:File -> settings -> Editor -> File and Code Templates -> Python Script

可选的内容:

#!/usr/bin/env python
# encoding: utf-8
#@author: caopeng
#@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
#@contact: deamoncao100@gmail.com
#@software: garner
#@file: ${NAME}.py
#@time: ${DATE} ${TIME}
#@desc:

# 常用变量
{PROJECT_NAME} - 当前项目的名称。
{NAME} - 在文件创建过程中在“新建文件”对话框中指定的新文件的名称。
{USER} - 当前用户的登录名。
{DATE} - 当前的系统日期。
{TIME} - 当前系统时间。
{YEAR} - 今年。
{MONTH} - 当月。
{DAY} - 当月的当天。
{HOUR} - 目前的小时。
{MINUTE} - 当前分钟。
{PRODUCT_NAME} - 将在其中创建文件的IDE的名称。
{MONTH_NAME_SHORT} - 月份名称的前3个字母。 示例:1月,2月等
{MONTH_NAME_FULL} - 一个月的全名。 示例:1月,2月等

推荐使用的内容:

##!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : ${DATE} ${TIME}
# @Author  : Mat
# @Email   : mat_wu@163.com
# @File    : ${NAME}.py

三引号的注释风格介绍

设置的位置:File > Settings > Tools > Python Integrated Tools > Docstrings

需要确保箭头的位置打对勾。在输入三引号后按回车会触发不同的模板。推荐Google

image-20211015225126259

# Plain
def foo1(a, b):
    """

    """
    return a+b

# reStructuredText
def foo2(a, b):
    """
    :param a:
    :param b:
    :return:
    """
    return a+b

# Numpy
def foo3(a, b):
    """
    Parameters
    ----------
    a
    b

    Returns
    -------

    """
    return a+b

# Google
def foo4(a, b):
    """
    Args:
        a:
        b:

    Returns:

    """
    return a + b

# Epytext
def foo(a, b):
    """
    @param a:
    @param b:
    @return:
    """
    return a+b

参考文档:

  1. PEP8
  2. python注释规范
  3. Pycharm 智能代码辅助功能
我的名片

昵称:shuta

职业:后台开发(python、php)

邮箱:648949076@qq.com

站点信息

建站时间: 2020/2/19
网站程序: ANTD PRO VUE + TP6.0
晋ICP备18007778号