Python Docstring 风格和写法学习

什么是Python Docstring

和Java类似,Python也通过注释形式的Docstring给程序、类、函数等建立文档。通过Docstring建立的文档不仅对人来说有更好的可读性,也能够让IDE等工具自动识别使用函数、类、变量等的一些限制,从而帮助我们更好地理解程序。

Python Docstring 的三种风格

总的来说,Python Docstring有三种主要风格,分别是reST风格、Google风格和Numpy风格:

reST的全称是 reStructredText。通过以冒号开头的几个关键字来说明类、函数中的参数、返回值、异常等。

例如我们要造一个双向链表的轮子,我们新建一个 DoubleLinkList.py 文件。其中包含两个类,一个是双向链表的节点类 DLLNode,一个是双向链表类 DoubleLinkList

首先看一下 DLLNode类。

class DLLNode(object):
"""
    The definition of node of double link list.

    :param val: The value of a node.

    :param prev: The pointer of the previous node of this node.

    :param next: The pointer of the next node of this node.

    :type val: Any
    :type prev: DLLNode, default None
    :type next: DLLNode, default None
"""

    def __init__(self, val, prev=None, next=None):
        self.val = val
        self.prev = prev
        self.next = next

我们可以看到在 DLLNode类中通过三个双引号 """建立了对DLLNode类的docstring。注意docstring必须位于任意其他代码的开头。在类的docstring中,常见的有如下声明标记:

:param <类属性名称>: <描述>
:type <类属性名称>: <类型>
</类型></类属性名称></描述></类属性名称>

其中,类型除了基本类型,如 intfloatstr等,还可以是列表类型 List[type],元组类型 Tuple[types],以及字典类型 Dict[KeyType, ValueType]等,还可以是各种模块中定义的类型。注意当类型为列表、元组或字典时与Python本身自带类型的不同。

这里我们不需要再对 DLLNode类中 __init__()函数添加docstring。在生成文档时,Python会自动将类的docstring复制给它的 __init__()函数。

下面再看一下 DoubleLinkList类。

class DoubleLinkList(object):
"""
    The definition of double link list.

    :param head: The head pointer of the list.

    :type head: DLLNode
"""
    def __init__(self, head):
        self.head = head

    def insert_node(self, val, node):
"""
        Insert a node before the node which data is val.

        :param val: The value to be find to insert a node before it.

        :param node: The node ready to insert.

        :type val: Any
        :type node: DLLNode
"""
        pass

    def remove_node(self, val):
"""
        Remove a node which data is val.

        :param val: The val of node to be removed.

"""
        pass

    def length(self):
"""
        Returns the length of this link table.

        :return: The length of this link table.

        :rtype: int
"""
        pass

    def search_node(self, val):
"""
        Search the first position of node which data equals val.

        :param val: The value to be searched.

        :return: The position of val first appeared.

        :rtype: int
"""
        pass

    def update_node(self, position, val):
"""
        Update the node in position by val.

        :param position: The position of the node to be updated.

        :param val: The target value of updated node.

        :type position: int
        :type val: Any
"""
        pass

假设我们给 DoubleLinkList类设计了增删改查和求长度五个方法。我们可以看到,除了 :param:type外,还有几个新的标签,列举如下:

:return: <对返回值的描述>
:rtype: <返回值类型>
:raises: <可能抛出的异常列表>
</可能抛出的异常列表></返回值类型></对返回值的描述>

当我们在docstring中为函数指定了 :param:type以后,如果在调用函数时给函数传入了错误的参数类型,IDE会发出warning,可以提醒我们传入正确的参数类型。

除了reST风格,Google Style也是一种常见的docstring规范。

仍以上文的 DoubleLinkList为例。Google Style的docstring如下:

class DLLNode(object):
"""
    The definition of node of double link list.

    Args:
        val (Any): The value of Node.

        prev (DLLNode): The previous node of this node.

        next (DLLNode): The next node of this node.

"""

    def __init__(self, val, prev=None, next=None):
        self.val = val
        self.prev = prev
        self.next = next

class DoubleLinkList(object):
"""
    The definition of double link list.

    Args:
        head (DLLNode): The head pointer of the link list.

"""
    def __init__(self, head):
        self.head = head

    def insert_node(self, val, node):
"""
        Insert a node before the node which data is val.

        Args:
            val (Any): The value to be find to insert a node before it.

            node (DLLNode): The node ready to insert.

"""
        pass

    def remove_node(self, val):
"""
        Remove a node which data is val.

        Args:
            val (DLLNode): The val of node to be removed.

"""
        pass

    def length(self):
"""
        Returns the length of this link table.

        Returns:
            int: The length of this link list.

"""
        pass

    def search_node(self, val):
"""
        Search the first position of node which data equals val.

        Args:
            val: The value to be searched.

        Returns:
            int: The first position of the searched value.

"""
        pass

    def update_node(self, position, val):
"""
        Update the node in position by val.

        Args:
            position (int): The position of node to be updated.

            val: The new value of target.

"""
        pass

与reST风格不同,Google Style将所有的参数写在 Args标签下,而所有的返回值写在 Returns标签下。我个人认为比起reST风格,Google Style的可读性要更好一些。在 Args标签下,可以在参数名称后面加 (&#x7C7B;&#x578B;)来确定参数的类型,同样可以起到对参数类型的限制作用。

Numpy是矩阵分析、科学计算、机器学习中都会用到的常见Python程序库。其文档详实完整,也是程序员们学习的典范之一。Numpy也有自己独特的Python Docstring风格。我们仍以 DoubleLinkList模块为例来说明。

class DLLNode(object):
"""
    The definition of node of double link list.

    Parameters
    ----------
    val : Any
        The value of node.

    prev : DLLNode
        The previous node of this node.

    next : DLLNode
        The next node of this node.

    Attributes
    ----------
    val : Any
        The value of node.

    prev : DLLNode
        The previous node of this node.

    next : DLLNode
        The next node of this node.

"""

    def __init__(self, val, prev=None, next=None):
        self.val = val
        self.prev = prev
        self.next = next

class DoubleLinkList(object):
"""
    The definition of double link list.

    Parameters
    ----------
    head : DLLNode
        The head pointer of the link list.

    Attributes
    ----------
    head : DLLNode
        The head pointer of the link list.

"""
    def __init__(self, head):
        self.head = head

    def insert_node(self, val, node):
"""
        Insert a node before the node which data is val.

        Parameters
        ----------
        val:
            The value to be find to insert a node before it.

        node : DLLNode
            The node ready to insert.

"""
        pass

    def remove_node(self, val):
"""
        Remove a node which data is val.

        Parameters
        ----------
        val :
            The val of node to be removed.

"""
        pass

    def length(self):
"""
        Returns the length of this link table.

        Returns
        -------
        int
            The length of this link list.

"""
        pass

    def search_node(self, val):
"""
        Search the first position of node which data equals val.

        Parameters
        ----------
        val:
            The value to be searched.

        Returns
        -------
        int
            The first position of the searched value.

"""
        pass

    def update_node(self, position, val):
"""
        Update the node in position by val.

        Parameters
        ----------
        position :int
            The position of node to be updated.

        val:
            The new value of target.

"""
        pass

和Google Style不同,Numpy Style采用如下格式描述一个类:

"""
&#x7C7B;&#x63CF;&#x8FF0;

Parameters
&#x5C5E;&#x6027; : [&#x7C7B;&#x578B;]
    &#x5C5E;&#x6027;&#x7684;&#x63CF;&#x8FF0;
"""

其中Parameters和Attributes可以不一样。具体区别我也不是搞得很明白。

函数描述如下

"""
&#x51FD;&#x6570;&#x63CF;&#x8FF0;

Parameters
&#x7C7B;&#x578B;
    &#x8FD4;&#x56DE;&#x503C;&#x7684;&#x63CF;&#x8FF0;

Raises
&#x8303;&#x4F8B;&#x63CF;&#x8FF0;

Yields(&#x4EC5;&#x9488;&#x5BF9;&#x751F;&#x6210;&#x5668;&#x51FD;&#x6570;)
&#x6CE8;&#x91CA;&#x5185;&#x5BB9;
"""

Numpy风格的docstring似乎不能用sphinx来生成html形式的文档。

本文介绍了Python程序设计中常见的三种docstring的风格,其中我个人认为Google Style相比之下是最好的一个,它既可以采用Sphinx来生成HTML格式的文档,也可以直接在命令行中通过help函数获得可读性更高的文档。但在Pycharm等IDE中,默认支持的是reST风格的。具体如何使用,就要看自己的喜好和项目要求了。

Original: https://www.cnblogs.com/ryuasuka/p/11085387.html
Author: 飞鸟_Asuka
Title: Python Docstring 风格和写法学习

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/609908/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • redis限流的3种实现方式

    Redis限流的实现方式有3种,分别是:1、基于Redis的setnx的操作,给指定的key设置了过期实践;2、基于Redis的数据结构zset,将请求打造成一个zset数组;3、…

    Linux 2023年5月28日
    0102
  • 【设计模式】Java设计模式-命令模式

    Java设计模式 – 命令模式 😄生命不息,写作不止🔥 继续踏上学习之路,学之分享笔记👊 总有一天我也能像各位大佬一样🏆 一个有梦有戏的人 @怒放吧德德🌝分享学习心得,…

    Linux 2023年6月6日
    086
  • 尤娜,我去面试了

    前情回顾 从前,有一个简单的通道系统叫尤娜…… 尤娜系统的第一次飞行中换引擎的架构垂直拆分改造 四种常用的微服务架构拆分方式 面试前几天 尤娜系统经过一次拆…

    Linux 2023年6月14日
    0110
  • linux的启动流程详解

    linux启动流程 一、第一阶段:BIOS 上个世纪70年代初,”只读内存”(read-only memory,缩写为ROM)发明,开机程序被刷入ROM芯片…

    Linux 2023年6月7日
    091
  • Linux 目录挂载服务

    Linux 服务器挂载文件目录通常有三种形式,手动挂载、自动挂载、Autofs 自动挂载,下面对这三个挂载做一下介绍,接受一下这三个区别以及使用场景: 准备服务器和客户端: ser…

    Linux 2023年6月6日
    099
  • Shell脚本完成IOS平台下的多目录和多架构编译(调用Makefile一起完成)

    博客园 :当前访问的博文已被密码保护 请输入阅读密码: Original: https://www.cnblogs.com/cy568searchx/p/5735429.htmlA…

    Linux 2023年5月28日
    0124
  • Django_模型详解

    Django_模型ORM Django中内嵌了ORM框架,不需要直接编写SQL语句进行数据库操作,而是通过定义模型类,操作模型类来完成对数据库中表的增删改查和创建等操作。 O是ob…

    Linux 2023年6月7日
    0117
  • linux三剑客之awk

    linux三剑客之awk 适用范围:awk主要是用来格式化文本。 语法格式:awk [参数] [处理规则] [操作对象] 参数 作用 -F 指定文本分隔符(不写默认是以空格作为分隔…

    Linux 2023年5月27日
    0112
  • 关于启动Docker容器的错误:OCI runtime create failed: container with id exists

    此笔记记载了本人在使用centos7.6环境下docker启动容器时遇到的 OCI runtime create failed: container with id exists:…

    Linux 2023年6月14日
    0107
  • haproxy

    haproxy 一.haproxy简介 二.负载均衡 三.haproxy安装 1.yum安装 2.源码安装 2.1 配置文件解析 2.2时间格式 2.3 全局global 2.4 …

    Linux 2023年6月7日
    0116
  • Linux 常用命令总结(三)

    一、实用命令 1、crontab(定时任务) (1)基本概念crontab 是用来管理定时任务的命令。系统启动后,将会自动调用 crontab,如果存在任务,则根据相关定义去执行。…

    Linux 2023年5月27日
    0123
  • 在Linux下的文件IO操作

    系统调用 为什么用户程序不能直接访问系统内核提供的服务,为了更好地保护内核空间,程序的运行空间被划分为内核空间和用户空间(俗称内核状态和用户模式),它们在不同的级别上逻辑上是相互隔…

    Linux 2023年5月27日
    093
  • RPA跨系统自动生成采购订单

    bash;gutter:true;1、从开发器启动机器人2、RPA登录友采云3、RPA根据筛选条件,导出采购订单4、RPA请并登录NC5、RPA把读取到的数据,逐个录入到NC系统中…

    Linux 2023年6月7日
    0138
  • Redis 基础

    Redis 基础 Redis 定位 – 特性 关系型数据库 特性 非关系型数据库 特性 Redis 特性 Redis 安装 – 启动 – 使用 …

    Linux 2023年6月13日
    0147
  • 5.3 Linux Vim三种工作模式

    通过前面的学习我们知道,Linux 系统中所有的内容都以文件的形式进行存储,当在命令行下更改文件内容时,常会用到文本编辑器。 我们首选的文本编辑器是 Vim(至于为什么,可查看《V…

    Linux 2023年6月7日
    0105
  • Django中自定义管理器Manager用法

    Django中Manager用法 第一种 class create_user(models.Manager): def create(self, name, sex, age): …

    Linux 2023年6月14日
    096
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球