Python 多行注释

Ary*_*sal 2 python comments

我在 Python 中挣扎于多行注释,我知道我可以#在每行多行注释"""的开头使用,但在注释的开头和结尾还有另一种使用方法;然而,在我的解释器中,该"""方法给出了一个输出而不是忽略注释。

>>> """this should
be a multi
line comment"""
Run Code Online (Sandbox Code Playgroud)

我的解释器给出了以下输出:

'this should\nbe a multi\nline comment'
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下吗?

The*_*Guy 10

许多开发人员使用三引号字符串作为注释,但它实际上不是注释。它类似于 python 中的常规字符串,但它允许字符串是多行的。您不会发现将三重引号字符串作为注释的官方参考。

在python中,只有一种以hash开头的注释类型,#并且只能包含一行文本。

根据PEP 257,它可以用作文档字符串,这又不是真正的注释。

def foo():
    """
    Developer friendly text for describing the purpose of function
    Some test cases used by different unit testing libraries
    """
   <body of the function>
   
Run Code Online (Sandbox Code Playgroud)

您可以像使用单引号字符串一样将它们分配给变量:

x = """a multi-line text
enclosed by
triple quotes
"""
Run Code Online (Sandbox Code Playgroud)

此外,如果你在 repl 中尝试它,三重引用的字符串会被打印出来,如果它真的是一条评论,它是否应该被打印出来?:

>>> #comment
>>> """triple quoted"""
'triple quoted'
Run Code Online (Sandbox Code Playgroud)