Skip to content

用reStructuredText语法为代码写注释

lyhuang18 edited this page Sep 15, 2018 · 4 revisions

例子

def my_function(my_arg, my_other_arg):
    """A function just for me.
    
    :param my_arg: The first of my arguments.
    :param str my_other_arg: The second of my arguments.
    :returns: A message (just for me, of course).
	
    This is an example::
	
        [
            [[word_11, word_12, word_13], [label_11. label_12]],  # sample 1
            [[word_21, word_22, word_23], [label_21. label_22]],  # sample 2
            ...
        ]

		
    This is an example:
	
    >>> a=1 
    >>> b=2
    >>> a+b
    3

    .. note:: 
        This is a note.
    
    """

Tips:

  1. :param arg:前必须空一行,才能显示出参数和返回值列表;在arg前面可以加上变量类型
  2. .. note::能生成一个note

插入代码片段

代码片段

如果是python代码,直接段落后面加 ::,并留一空行,被引用的代码,还要以tab或等量的空格进行缩进,如下面例子:

python使用如下语法定义list,list的元素类型可以不一样::

    >>> a = ['spam', 'eggs', 100, 1234]
    >>> a
    ['spam', 'eggs', 100, 1234]

也可以这样:

.. code-block:: python

    a = ['spam', 'eggs', 100, 1234]
    a
    ['spam', 'eggs', 100, 1234]

代码包含

引用外部的源代码文件,例子如下:

.. literalinclude:: ../code/threading_1.py
   :language: python
   :linenos:
   :lines: 1,3,5-10,20-1234

显示代码方面的更详细的资料,可以查看 http://www.pythondoc.com/sphinx/markup/code.html

插入数学公式

当将数学标记放在由autodoc读取的Python文档字符串中时,必须将所有反斜杠加倍,或者使用Python原始字符串(r“raw”)。

class MaskedGRU(MaskedRNNBase):
    r"""Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence.
    For each element in the input sequence, each layer computes the following
    function:

    .. math::
        \begin{array}{ll}
        r_t = \mathrm{sigmoid}(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\
        z_t = \mathrm{sigmoid}(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\
        n_t = \tanh(W_{in} x_t + b_{in} + r_t * (W_{hn} h_{(t-1)}+ b_{hn})) \\
        h_t = (1 - z_t) * n_t + z_t * h_{(t-1)} \\
        \end{array}
    """

注意:.. math::前空一行

插入数学公式方面的更详细的资料,可以查看 http://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#math

其他可能会用到的

列表

使用*号表示一组列表,#.表示有序列表,例子如下:

* This is a bulleted list.
* It has two items, the second
  item uses two lines.

1. This is a numbered list.
2. It has two items too.

#. This is a numbered list.
#. It has two items too.123456789

行内标记

*text* 斜体
**text** 加粗
``text`` 代码引用
Clone this wiki locally