简体   繁体   English

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

[英]Why wasn't the string at the top of this function printed?

I encountered the following function in a tutorial. 我在教程中遇到了以下函数。 When I call the function, "This prints a passed string into this function" isn't printed. 当我调用该函数时,不会打印"This prints a passed string into this function" Why does the function not print this piece of text when called? 为什么函数在调用时不打印这段文本?

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")

What you're seeing there is a document string, or docstring in short. 您所看到的是文档字符串或简称docstring

A docstring is a string that is supposed to document the thing it is attached to. docstring是一个字符串,用于记录它所附加的东西。 In your case, it is attached to a function, and as such is supposed to document the function. 在您的情况下,它附加到一个函数,因此应该记录该函数。 You can also have docstrings for classes and modules. 您还可以拥有类和模块的文档字符串。

You create docstrings by simply placing a string on its own as the very first thing in a function (or class, or module). 您可以通过简单地将字符串放在函数(或类或模块)中的第一件事来创建文档字符串。 The interpreter will then use it as a docstring and make it available in special the __doc__ attribute: 然后,解释器将其用作文档字符串,并使其在特殊的__doc__属性中可用:

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

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

Docstrings are also used by the help() function: doc help()函数也使用文档字符串:

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

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

The common practice for docstrings, to make it clear that they are supposed to be actual docstrings and not just misplaced “proper” strings, is to use triple quotes. 文档字符串的常见做法是,使用三重引号来明确它们应该是实际的文档字符串,而不仅仅是错误的“正确”字符串。 Triple quotes are used to create multi-line strings which in addition allows docstrings to be multi-line too: 三引号用于创建多行字符串,此外,文档字符串也可以是多行的:

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)

Various docstring conventions are also described in PEP 257 . PEP 257中还描述了各种文档字符串约定。

It does get executed, however evaluating and the never using a string is effectively a no-op. 它确实被执行,但是评估和从不使用字符串实际上是一个无操作。 The reason it works in the REPL is beacuse the REPL is the RE P L, that is the read eval print loop. 它在REPL中工作的原因是REPL是RE P L,即读取eval 打印循环。 The print step does not exists in ordinary execution. 普通执行中不存在打印步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM