三双报价与双重报价

Min*_*gyu 26 python docstring pep8 pep quote

编写Python文档字符串的首选方法是什么?

""" 要么 "

Dive Into Python一书中 ,作者提供了以下示例:

def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""
Run Code Online (Sandbox Code Playgroud)

在另一章中,作者提供了另一个例子:

def stripnulls(data):
    "strip whitespace and nulls"
    return data.replace("\00", "").strip()
Run Code Online (Sandbox Code Playgroud)

两种语法都有效.对我来说唯一的区别是"""允许我们编写多行文档.

除此之外有什么区别吗?

unu*_*tbu 35

PEP8风格指南:

  • PEP 257描述了良好的文档字符串约定.请注意,最重要的是,结束多行文档字符串的"""应该在一行上,例如:

    """Return a foobang
    
    Optional plotz says to frobnicate the bizbaz first.
    """
    
    Run Code Online (Sandbox Code Playgroud)
  • 对于一个班轮文档字符串,可以将结束""保持在同一行.

PEP 257建议使用三重引号,即使对于单行文档字符串:

  • 即使字符串适合一行,也会使用三重引号.这使得以后扩展它变得容易.

请注意,即使Python标准库本身也不一致地遵循这些建议.例如,


Ble*_*der 6

它们都是字符串,所以没有区别.首选的风格是三重双引号(PEP 257):

为了保持一致性,请始终使用"""triple double quotes"""docstrings.

使用r"""raw triple double quotes""",如果你在你的文档字符串使用任何反斜线.对于Unicode文档字符串,请使用u"""Unicode triple-quoted strings""".