个性化阅读
专注于IT技术分析

Python中的文档字符串

本文概述

下面提到的规则仅是一个约定, 并且它们严格基于PEP标准。它们不是规则或Python语法。

本教程将包含:

  • 单行文档字符串
  • 多行文档字符串
  • 流行的文档字符串格式
  • 流行的文档字符串格式
    • 斯芬克斯风格
    • Google风格
    • 脾气暴躁的风格
  • Python内置文档字符串

文件串

Python Docstring是文档字符串, 它是字符串文字, 它出现在类, 模块, 函数或方法定义中, 并作为第一条语句编写。可以从任何Python对象的doc属性访问文档字符串, 并且还可以使用内置的help()函数派上用场。

此外, 文档字符串对于理解代码大部分的功能(即任何类, 模块或函数的通用目的)非常有用, 而注释则用于代码, 语句和表达式, 而这些注释, 注释和表达式往往很小。它们是程序员编写的描述性文本, 主要是为了自己了解代码行或表达式的功能。这是必不可少的部分, 文档代码将足以编写干净的代码和编写良好的程序。尽管已经提到, 但没有标准和规则。

编写文档字符串有两种形式:单行文档字符串和多行文档字符串。这些是数据科学家/程序员在其项目中使用的文档。

单行文档字符串

单行Docstrings是适合所有一行的Docstrings。你可以使用其中一种引号, 即三重单引号或三重双引号, 并且开头和结尾的引号必须相同。在单行文档字符串中, 右引号与右引号位于同一行。同样, 标准约定是使用三重双引号。

def square(a):
    '''Returns argument a is squared.'''
    return a**a

print (square.__doc__)


help(square)
Returns argument a is squared.
Help on function square in module __main__:

square(a)
    Returns argument a is squared.

在上面的代码中, 你将获得打印结果:

Returns argument a is squared.
Help on function square in module __main__:

square(a)
    Returns argument a is squared.

在上面的文档字符串中, 你可以观察到:

  1. 该行以大写字母开头, 即本例中的R, 以句点(“。”)结尾。
  2. 结束语与开始语在同一行。对于单线而言, 这看起来更好。
  3. Docstring之前或之后没有空白行。这是一个好习惯。
  4. 上面的引号行比最后以句号结尾的描述更具说服力。

多行文档字符串

多行文档字符串还包含与单行文档字符串中相同的字符串文字行, 但是其后是单个空格以及描述性文本。

编写多行文档字符串的一般格式如下:

def some_function(argument1):
    """Summary or Description of the Function

    Parameters:
    argument1 (int): Description of arg1

    Returns:
    int:Returning value

   """

    return argument1

print(some_function.__doc__)
Summary or Description of the Function

    Parameters:
    argument1 (int): Description of arg1

    Returns:
    int:Returning value

上面的代码输出:

Summary or Description of the Function

    Parameters:
    argument1 (int): Description of arg1

    Returns:
    int: Returning value

让我们看一个示例, 该示例可以显示如何详细使用多行字符串:

def string_reverse(str1):
    """ Returns the reversed String.

    Parameters:
        str1 (str):The string which is to be reversed.

    Returns:
        reverse(str1):The string which gets reversed.   

    """
    reverse_str1 = ''
    i = len(str1)
    while i > 0:
        reverse_str1 += str1[ i - 1 ]
        i = i- 1
    return reverse_str1
print(string_reverse('projkal998580'))
085899lakjorp

你可以在上方看到摘要行在一行上, 并且还与其他内容用一个空白行隔开。需要遵守该约定, 这对于自动索引工具很有用。

流行的文档字符串格式

有许多Docstrings格式可用, 但是使用Docstring解析器以及其他数据科学家/程序员容易识别的格式总是更好的选择。没有选择文档字符串格式的任何规则和规定, 但是在项目中选择相同格式的一致性是必需的。另外, 最好使用Sphinx支持的格式类型。下面列出了最常用的格式。

格式化类型 描述
NumPy / SciPy文档字符串 由Sphinx支持的reStructured和GoogleDocstrings的组合
皮多克 Sphinx支持的Python标准文档模块
埃皮多克 将Epytext渲染为一系列HTML文档, 以及一个根据PythonDoc的Docstrings为Python模块生成API文档的工具
Google Docstrings Google的风格

流行的文档字符串格式

可能会有不同的文档字符串。你不必担心必须重新发明轮子才能全面研究这一事实。所有文档字符串的格式几乎相似。模式是相似的, 但是每种格式只有细微的变化。你将看到一个流行的格式文档字符串示例, 该文档字符串可随其使用。首先, 你将详细了解Sphinx样式, 并且可以轻松地与其他格式一起使用。

狮身人面像风格

Sphinx是简单而传统的样式, 冗长, 最初是专门为Python文档创建的。 Sphinx使用reStructuredText, 其用法与Markdown相似。

class Vehicle(object):
    '''
    The Vehicle object contains lots of vehicles
    :param arg: The arg is used for ...
    :type arg: str
    :param `*args`: The variable arguments are used for ...
    :param `**kwargs`: The keyword arguments are used for ...
    :ivar arg: This is where we store arg
    :vartype arg: str
    '''


    def __init__(self, arg, *args, **kwargs):
        self.arg = arg

    def cars(self, distance, destination):
        '''We can't travel a certain distance in vehicles without fuels, so here's the fuels

        :param distance: The amount of distance traveled
        :type amount: int
        :param bool destinationReached: Should the fuels be refilled to cover required distance?
        :raises: :class:`RuntimeError`: Out of fuel

        :returns: A Car mileage
        :rtype: Cars
        '''  
        pass

Sphinx使用”关键字(保留字)”, 大多数编程语言都使用。但是在狮身人面像中它被专门称为”角色”。在上面的代码中, Sphinx具有” param”作为角色, 而” type”是作为” param”的Sphinx数据类型的角色。 “类型”角色是可选的, 但”参数”是必需的。返回角色记录了返回的对象。它与param角色不同。返回角色不依赖于rtype, 反之亦然。 rtype是从给定函数返回的对象的类型。

Google风格

Google样式更易于使用, 更直观。它可以用于简短的文档形式。需要完成python文件的配置才能上手, 因此你需要在conf.py的扩展名列表中添加sphinx.ext.napoleon或sphinxcontrib.napoleon。

class Vehicles(object):
    '''
    The Vehicle object contains a lot of vehicles

    Args:
        arg (str): The arg is used for...
        *args: The variable arguments are used for...
        **kwargs: The keyword arguments are used for...

    Attributes:
        arg (str): This is where we store arg, '''
    def __init__(self, arg, *args, **kwargs):
        self.arg = arg

    def cars(self, distance, destination):
        '''We can't travel distance in vehicles without fuels, so here is the fuels

        Args:
            distance (int): The amount of distance traveled
            destination (bool): Should the fuels refilled to cover the distance?

        Raises:
            RuntimeError: Out of fuel

        Returns:
            cars: A car mileage
        '''
        pass

Google样式优于Sphinx样式。它还具有一个不便的功能, 即在上面的代码中, 距离的多行描述看起来很混乱。这就是为什么可以将Numpy用于更扩展的文档形式。

脾气暴躁的风格

Numpy样式在文档中有很多细节。它比其他文档更加冗长, 但是如果你要进行详细的文档(即, 所有功能和参数的详尽文档), 它是一个绝佳的选择。

class Vehicles(object):
    '''
    The Vehicles object contains lots of vehicles

    Parameters
    ----------
    arg : str
        The arg is used for ...
    *args
        The variable arguments are used for ...
    **kwargs
        The keyword arguments are used for ...

    Attributes
    ----------
    arg : str
        This is where we store arg, '''
    def __init__(self, arg, *args, **kwargs):
        self.arg = arg

    def cars(self, distance, destination):
        '''We can't travel distance in vehicles without fuels, so here is the fuels

        Parameters
        ----------
        distance : int
            The amount of distance traveled
        destination : bool
            Should the fuels refilled to cover the distance?

        Raises
        ------
        RuntimeError
            Out of fuel

        Returns
        -------
        cars
            A car mileage
        '''
        pass

上面的示例比其他任何文档都更冗长。它比较冗长, 只能用于冗长而详细的文档。

Python内置文档字符串

你还可以查看内置的Python文档字符串。

所有内置函数, 类, 方法均附有实际的人工描述。你可以通过以下两种方式之一来访问它。

  1. doc属性
  2. 帮助功能

例如

import time
print(time.__doc__)
This module provides various functions to manipulate time values.

There are two standard representations of time.  One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
The actual value can be retrieved by calling gmtime(0).

The other representation is a tuple of 9 integers giving local time.
The tuple items are:
  year (including century, e.g. 1998)
  month (1-12)
  day (1-31)
  hours (0-23)
  minutes (0-59)
  seconds (0-59)
  weekday (0-6, Monday is 0)
  Julian day (day in the year, 1-366)
  DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.

上面的代码将给出:

This module provides various functions to manipulate time values.

There are two standard representations of time.  One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
The actual value can be retrieved by calling gmtime(0).
.............................................
............................................
............................................
.............................................
more description..........................

同样, 可以通过以下方式使用该帮助:

help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

上面的代码返回

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

恭喜!

你已经完成了本教程的结尾!在此过程中, 你已经了解了Docstrings, 它是用于记录程序员和数据科学家的基本工具。你可以在Python网站Python DocStrings PEP257上了解更多信息。

如果你想了解有关Python的更多信息, 请参加srcmini的数据科学中级Python课程。

赞(0)
未经允许不得转载:srcmini » Python中的文档字符串

评论 抢沙发

评论前必须登录!