python - 为什么不打印此函数顶部的字符串?

标签 python docstring

我在教程中遇到了以下功能。当我调用函数时,"This prints a passed string into this function" 没有被打印出来。为什么函数调用时不打印这段文字?

def printme(str):
   "This prints a passed string into this function"
   print str
   return

# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

最佳答案

您看到的是一个文档字符串,或者简称为 docstring

文档字符串是一个字符串,应该记录它所附加的东西。在您的情况下,它附加到一个函数,因此应该记录该函数。您还可以拥有类和模块的文档字符串。

您可以通过简单地将字符串作为函数(或类或模块)中的第一件事来创建文档字符串。解释器然后将其用作文档字符串并使其在特殊的 __doc__ 属性中可用:

>>> def printme( str ):
        "This prints a passed string into this function"
        print str

>>> printme.__doc__
'This prints a passed string into this function'

文档字符串也被 help() 函数使用:

>>> help(printme)
Help on function printme in module __main__:

printme(str)
    This prints a passed string into this function

文档字符串的常见做法是使用三重引号,以明确它们应该是实际的文档字符串,而不仅仅是放错位置的“正确”字符串。三重引号用于创建多行字符串,此外还允许文档字符串也是多行的:

def printme (str):
    '''
    Print the string passed in the `str` argument to the
    standard output. This is essentially just a wrapper
    around Python’s built-in `print`.
    '''
    print(str)

PEP 257 中还描述了各种文档字符串约定。 .

关于python - 为什么不打印此函数顶部的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33156785/

相关文章:

Python + Mechanize 不适用于 Delicious

python - 如何获取有序集?

Python - Selenium : Find/Click YT-Like Button

python - 将 excel 嵌入到 gui 中,用于 python 程序

python - 你如何修复 "Missing module docstringpylint(missing-module-docstring)"

numpy - NumPy 如何将文档字符串处理为参数的 sphinx 文档?

objective-c - 为 Xcode 5 的快速帮助⁣帮助创建枚举文档字符串

python - 使用 pylint 文档参数时减少 Python 文档字符串中的冗余

python - 简化python中的类docstring

python - 将两列串联成一轮 float