Python Docstring style and writing learning

What is Python Docstring

And similar to Java, Python also create documents to the program, classes, functions, etc. through the comment form Docstring. Documents created by Docstring not only for people, better readability, but also allows IDE tools such as automatic identification using some restrictions functions, classes, variables, etc., to help us better understand the program.

Python Docstring of three styles

In general, Python Docstring There are three main styles, namely reST style, Google style and Numpy Style:

reST style

reST stands reStructredText . By the beginning of the colon of several key parameters described classes, the function returns a value, and other abnormalities.

For example, we want to build a doubly linked list of the wheel, we create a new DoubleLinkList.pyfile. It contains two classes, a class is a doubly linked list of nodes DLLNode, is a doubly linked list type DoubleLinkList.

First, look at the DLLNodeclass.

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

We can see in DLLNodethe class by three pairs of quotation marks """established docstring of DLLNode class. Note docstring must be located at the beginning of any other code. In the class docstring in common with the following statement marking:

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

Wherein, in addition to the type of basic types, such as int, float, strand the like, also may be a list type List[type], tuples Tuple[types], dictionaries and Dict[KeyType, ValueType]the like, may also be of the type defined in the various modules. Note that when a different type of itself comes with Python type is a list or dictionary tuples.

Here we do not need to DLLNodetype in __init__()to add docstring function. When generating documentation, Python docstring of the class is automatically copied to its __init__()function.

Here's look at DoubleLinkListthe class.

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

Suppose we gave DoubleLinkListclass design requirements and length CRUD five methods. We can see that in addition to :paramand :typeoutside, there are several new tags are listed below:

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

When we specify a function in the docstring :paramand :typelater, if passed the wrong type of parameters to a function when you call the function, IDE will issue a warning, a reminder we pass the correct parameter type.

Google Style

In addition to reST style, Google Style docstring is also a common specification.

Still above DoubleLinkListexample. Google Style's docstring as follows:

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 with different styles, Google Style all parameters written Argsunder the label, and all return values written on the Returnslabel. I personally think than reST style, Google Style To better readability. In Argsthe label, may be added after the name of the parameter (类型)to determine the type of the parameter, can also play a limiting effect on the parameter type.

Numpy Style

Numpy is a matrix analysis, scientific computing, common Python library will be used in machine learning. One document detailed and complete, but also programmers learning model. Numpy also has its own unique style of Python Docstring. We still DoubleLinkListmodule as an example to illustrate.

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

Different Google Style, Numpy Style following format to describe a class:

"""
类描述

Parameters
----------
参数 : [类型]
    参数的描述
    
Attributes
----------
属性 : [类型]
    属性的描述
"""

Parameters and Attributes which can be different. Specific difference is I do not quite understand.

Functions described below

"""
函数描述

Parameters
----------
参数 : [类型]
   参数的描述

Returns
-------
类型
    返回值的描述
    
Raises
------
异常名称
    异常描述

Examples
--------
范例描述

Yields(仅针对生成器函数)
------
类型
   生成器返回值描述
 
Note
----
注释内容
"""

Numpy style docstring not seem to generate the html form of the document with the sphinx.

summary

This article describes three common docstring style of programming in Python, which I personally think that Google Style contrast is one of the best, both Sphinx to generate documentation in HTML format can be used, or directly from the command line get more readable document through the help function. But Pycharm such as IDE, is supported by default reST style. How you use, depends on your preferences and requirements of the project.

Guess you like

Origin www.cnblogs.com/ryuasuka/p/11085387.html