Python有一個很奇妙的特性,稱為 文檔字符串 ,它通常被簡稱為 docstrings 。DocStrings是一個重要的工具,由于它幫助你的程序文檔更加簡單易懂,你應(yīng)該盡量使用它。你甚至可以在程序運行的時候,從函數(shù)恢復(fù)文檔字符串!

#!/usr/bin/python
#
 Filename: func_doc.py
def printMax(x, y):
    
'''Prints the maximum of two numbers.
    The two values must be integers.
'''
    x 
= int(x) # convert to integers, if possible
    y = int(y)
    
if x > y:
        
print x, 'is maximum'
    
else:
        
print y, 'is maximum'
printMax(
35)
print printMax.__doc__ 
輸出
$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.
        The two values must be integers.

它如何工作
在函數(shù)的第一個邏輯行的字符串是這個函數(shù)的 文檔字符串 。注意,DocStrings也適用于模塊和
類,我們會在后面相應(yīng)的章節(jié)學(xué)習(xí)它們。
文檔字符串的慣例是一個多行字符串,它的首行以大寫字母開始,句號結(jié)尾。第二行是空行,
從第三行開始是詳細的描述。
強烈建議 你在你的函數(shù)中使用文檔字符串時遵循這個慣例。
你可以使用__doc__(注意雙下劃線)調(diào)用printMax函數(shù)的文檔字符串屬性(屬于函數(shù)的名
稱)。請記住Python把 每一樣?xùn)|西 都作為對象,包括這個函數(shù)。