为什么python要求缩进文档字符串?

0 python

python为什么接受此代码:

def is_right_triangle(leg1,leg2,hypotenuse):
    """function for checking whether or not set of points makes a right triangle"""
    return leg1 ** 2 + leg2 ** 2  == hypotenuse ** 2
Run Code Online (Sandbox Code Playgroud)

但是在这段代码中,文档字符串没有缩进

def is_right_triangle(leg1,leg2,hypotenuse):
 """function for checking whether or not set of points makes a right triangle"""
    return leg1 ** 2 + leg2 ** 2  == hypotenuse ** 2
Run Code Online (Sandbox Code Playgroud)

它将引发“预期的缩进块”错误。

为什么python关心文档字符串是否缩进?

vir*_*tor 5

因为文档字符串只是函数中的另一个表达式。它只是以特殊的方式处理,因为它是一个字符串和第一个表达式。

您还可以通过获取函数ast来看到这一点:

> a=ast.parse('def f(x):\n    "docstring"\n    return 0')
> a.body[0].body
[<_ast.Expr at 0x7f18bb3e6a20>, <_ast.Return at 0x7f18bb3e6550>]
> a.body[0].body[0].value.s
'docstring'
Run Code Online (Sandbox Code Playgroud)