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 的集成开发环境(>>>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__”属性来获取它的文档字符串。
文档字符串的标准格式:
文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。强烈建议 你在你的函数中使用文档字符串时遵循这个惯例。