• 技术文章 >后端开发 >Python教程

    解析Python代码注释规范代码

    coldplay.xixicoldplay.xixi2020-08-15 17:18:41转载1986

    一、代码注释介绍

    相关学习推荐: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 + 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代码注释规范代码的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:jb51,如有侵犯,请联系admin@php.cn删除
    专题推荐:python 代码注释 规范
    上一篇:Python代码是什么语言 下一篇:掌握python 19个值得学习的编程技巧
    大前端线上培训班

    相关文章推荐

    • PHP 代码注释• PHP代码注释小细节• 深入理解JS代码注释方法及代码注释规范• 基于TPC-C基准的Python ORM的性能测试详解

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网