简体   繁体   中英

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. 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.

A docstring is a string that is supposed to document the thing it is attached to. 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:

>>> 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:

>>> 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 .

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. The print step does not exists in ordinary execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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