• Python学习笔记之疑问 3:''' 三重引号(three double-quotes)的作用


    在Python经常会看到''' 这种符号。

    例如:

    print """
    There's something going on here.
    With the three double-quotes.
    We'll be able to type as much as we like.
    Even 4 lines if we want, or 5, or 6.
    """

    表示一个多行的字符串。在开始引号和结束引号之间的所有东西都属于一个单独的字符串的一部分,包括回车、前导空格、和其他引号字符。另外,如果字符串中即包含单引号,又包含多引号时也可以用三重引号(
    three double-quotes

    但是你会发现大部分时候它们在定义docstring (文档注释)的时候使用。

    例如:

    def approximate_size(size, a_kilobyte_is_1024_bytes=True):
       
    '''Convert a file size to human-readable form.

        Keyword arguments:
        size -- file size in bytes
        a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
                                    if False, use multiples of 1000

        Returns: string

        '''
    这个文档描述相当于对这个函数的描述,以方便自己或其它程序员理解函数,另外,还有一个非常重要的作用:
    很多 Python 的集成开发环境(ide)使用 docstring (文档字符串)来提供上下文敏感的文档,以便于当你输入一个函数名称的时候,它的 docstring 会以一个提示文本的方式显式出来。这可能会极其有用,但它只有在你写出好的 docstring (文档字符串)的时候才有用。

    如何在代码中查看引用的模块的文档字符串呢?

    >>>import humansize
    >>>print(humansize.approximate_size(4096,True))
    4.0KiB>>>print(humansize.approximate_size.__doc__)

    Convert a file size to human-readable form.

    Keyword arguments:
    size -- file size in bytes
    a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
    if False, use multiples of 1000

    Returns: string

    注意,是使用了函数的“__doc__”属性来获取它的文档字符串。
    文档字符串的标准格式:
    文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。 强烈建议 你在你的函数中使用文档字符串时遵循这个惯例。

     

  • 相关阅读:
    centos6:一个网卡上显示多个ip地址的错误
    博客搬家到CSDN:http://blog.csdn.net/yeweiouyang
    Codeforces Round #430 (Div. 2)
    Codeforces Round #430 (Div. 2)
    Codeforces Round #430 (Div. 2)
    Codeforces Round #426 (Div. 2)
    Codeforces Round #427 (Div. 2)
    Codeforces Round #427 (Div. 2)
    Codeforces Round #427 (Div. 2)
    Codeforces Round #427 (Div. 2)
  • 原文地址:https://www.cnblogs.com/littleebeer/p/3352790.html
Copyright © 2020-2023  润新知