2014-04-29 54 views
6

所以我明白,如果我做了以下三重報價

print """ Anything I 
      type in here 
      works. Multiple LINES woohoo!""" 

但是,如果下面是我的python腳本

""" This is my python Script. Just this much """ 

是什麼上面的東西做什麼?它是作爲評論嗎?爲什麼它不是一個語法錯誤?

同樣,如果我做

"This is my Python Script. Just this. Even with single quotes." 

如何在上述兩個腳本解釋?

感謝

回答

10

三重引號'''"""是代表弦的不同方式。三重引號的優點是它可以跨越多行,有時可以作爲docstrings

原因:

"hadfasdfas"

不會引發任何錯誤是因爲Python只是簡單的創建字符串,然後不把它分配給什麼。對於python解釋器來說,只要沒有語法或語義錯誤,只要你的代碼中有無意義的語句就沒問題了。

希望有幫助。

2

該字符串只是被評估,並且解釋器注意到它沒有被分配給任何東西,將其扔掉。

但在一些特殊的地方,這個字符串實際上是分配給項目的__doc__屬性:

def func(arg): 
    """ 
    Does stuff. This string will be evaluated and assigned to func.__doc__. 
    """ 
    pass 

class Test: 
    """ 
    Same for Test.__doc__ 
    """ 
    pass 

截至module.py頂部:

""" 
module does stuff. this will be assigned to module.__doc__ 
""" 
def func(): 
... 
+2

實際上在docstrings中它被綁定到'func .__ doc__' – wim

+0

是的,我錯過了。謝謝 – MadeOfAir

1

除了@ sshashank124回答我不得不補充說,三重引號字符串也用於測試https://docs.python.org/2/library/doctest.html

因此,請考慮這段代碼片段:

def some_function(x, y): 
"""This function should simply return sum of arguments. 
It should throw an error if you pass string as argument 

>>> some_function(5, 4) 
9 
>>> some_function(-5, 4) 
-1 
>>> some_function("abc", 4) 
Traceback (most recent call last): 
    ... 
ValueError: arguments must numbers 
""" 
if type(x, str) or type(y, str): 
    raise ValueError("arguments must numbers") 
else: 
    return x + y 

if __name__ == "__main__": 
    import doctest 
    doctest.testmod() 

如果你導入這個小模塊,你會得到some_function函數。
但是,如果您直接從shell調用此腳本,則會評估三重引號字符串中給出的測試,並將報告輸出到輸出。

因此,可以將三重引用的字符串視爲字符串類型的值,作爲註釋,作爲文檔字符串和作爲單元測試的容器。

+0

我不明白,當我運行這個腳本時究竟發生了什麼。首先,我不確定x和y的價值是什麼?你能否詳細說明一下。謝謝 – Kraken

+0

如果將它保存爲擴展名爲'.py'的文件,比如'some_module.py',它就會成爲一個模塊。如果你導入它,那麼'__name__ ==「__main __」'是'False',所以沒有魔法發生。但是如果你從shell調用它,'python some_module.py'最後兩行被執行。在這種情況下,'doctest.testmod()'將掃描Python單元測試的文檔字符串。所以它找到'>>>'這意味着'執行'。在我的片段中,第一個unittest調用'some_function(5,4)'。此調用的預期結果放在下一行。有時會發生異常,就像第三次單元測試一樣。如果結果符合預期,則測試成功。 – ElmoVanKielmo