我在教程中遇到了以下功能。当我调用函数时,"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/