zoukankan      html  css  js  c++  java
  • python常识系列10-->python代码注释规范

    前言

        成功的法则极为简单,但简单并不代表容易。
    

    一、代码注释介绍

    • 注释就是对代码的解释和说明,其目的是让人们能够更加轻松地了解代码。
    • 注释是编写程序时,写程序的人给一个语句、程序段、函数等的解释或提示,能提高程序代码的可读性。
    • 在有处理逻辑的代码中,源程序有效注释量必须在20%以上。

    二、代码注释分类

    • 行注释:在符号后那一行不会被编译(显示)
    • 块注释:被块注释符号中间的部分不会被编译

    三、python代码注释基础

    1. Python中使用#表示单行注释。单行注释可以作为单独的一行放在被注释代码行之上,也可以放在语句或表达式之后。如下例子:
    name = 'xiaohong'  # 单行注释
    
    # 单行注释
    name = 'xiaohong' 
    
    1. 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
    """
    

    六、一些注释经验

    • 注释不是越多越好。对于一目了然的代码,不需要添加注释。
    • 对于复杂的操作,应该在操作开始前写上相应的注释。
    • 对于不是一目了然的代码,应该在代码之后添加注释。
    • 绝对不要描述代码。一般阅读代码的人都了解Python的语法,只是不知道代码要干什么
  • 相关阅读:
    jquery.validate验证表单配合回调提交和h5.storage本地保存笔记
    datetimepicker时间控件
    画图工具除了echarts我使用highcharts
    jquery.bootpag分页控件
    时间插件--做到前几个月和后个几月的设置
    websocket小荔枝
    jquery请求解析xml
    【leetcode】Combinations
    【leetcode】Balanced Binary Tree
    【leetcode刷题笔记】Remove Duplicates from Sorted Array II
  • 原文地址:https://www.cnblogs.com/dream66/p/12826947.html
Copyright © 2011-2022 走看看