2015-10-15 65 views
4

我在教程中遇到以下功能。當我打電話功能時,"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") 
+4

因爲字符串不是'打印'。 –

+0

我明白了,但如果在終端輸入「hello」,在終端中正常使用python時,會返回「hello」?這是一個具體的區別適用? – user2713650

+0

這是因爲IDLE具有與實際運行腳本不同的行爲。 –

回答

10

你所看到的有一個文檔字符串,或簡稱爲docstring

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也有描述。

5

它確實得到執行,但是評估和從不使用字符串實際上是沒有操作的。它在REPL中起作用的原因是因爲REPL是RE,即讀取評估print循環。普通執行中不存在打印步驟。

+0

權利,使很多感,謝謝! – user2713650

相關問題