Python Docstrings

我们可以在python程序中对代码进行注释,以了解部分代码。但是要搜索注释和注释的不同部分,我们需要使用search(CTL + F),并滚动许多行。同样,我们还没有立即知道给定单词与代码的多少个部分相关联的直接方法。为了解决此问题,我们提供了python Docstring,它在定义函数,模块,类或方法之后立即访问字符串。

打印文档字符串

当__doc__属性在定义对象后立即声明时,它会自动与python对象的名称相关联。下面的例子使之很清楚。

例子

def Add_nums(x):
   '''Ada a number to itself.'''
   return x + x
print(Add_nums.__doc__)

输出

运行上面的代码给我们以下结果-

Ada a number to itself.

单行与多行文档

单行文档字符串只有一行,因此描述性不应太强。它们用字符串的开头和结尾的三引号引起来。上面的示例是单行docstring。

多行文档字符串

有时我们可能需要更详细地描述模块或功能。在这种情况下,我们使用多行文档字符串。它们显示一个摘要行,就像一个单行文档字符串,然后显示一个空行,后面是更详细的描述。

例子

def Fibonacci(n):
   '''The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .'''
   return x + x
print(Fibonacci.__doc__)

输出

运行上面的代码给我们以下结果-

The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .

内置Python对象的文档字符串

通过使用类名和__doc__,我们可以轻松访问与python对象(如函数,模块等)相关的文档。

例子

print(list.__doc__)

输出

运行上面的代码给我们以下结果-

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.

Docstrings中的缩进

文档字符串第一行中的任何缩进(即,直到第一换行符)都是无关紧要的并已删除。保留文档字符串中后面几行的相对缩进。整个文档字符串的缩进与其第一行的引号相同。