Python 入門指南

單元 13 - 文件字串

本書已有新版,請參考 Python 入門指南 5.00 - 目錄

~~學習進度表~~

文件字串 (documentation string) 定義在模組 (module) 、函數 (function) 、類別 (class) 及方法 (method) 中,用為程式的說明文件,可用預設屬性 (attribute) __doc__ 存取

__doc__

說明文件不外是解釋程式某部分的使用方式,通常會舉出簡單的例子,傳統程式語言 (programming language) 的說明文件大都是額外編寫,印成紙書或放在網路供人查詢,或是以註解 (comment) 形式加進原始程式碼 (source code) 中, Python 文件字串的特點讓程式設計師可以邊寫程式邊查文件,無須翻紙書或查網路。

我們先進入 Python 的互動式介面來看看吧!下面印出內建函數 int() 的屬性 __doc__

$ python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 05:52:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(int().__doc__)
int(x=0) -> integer
int(x, base=10) -> integer
 
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
>>>

int() 用來建立整數物件 (object) ,因此回傳一個整數物件,這裡可以看到 int() 的解釋與用法。

下面再來看看串列 (list) 的文件字串

>>> print([].__doc__)
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
>>>

串列的文件字串只有簡單印出用法,大體上文件字串是依需要來設置。文件字串分成兩種,一種是單行的文件字串,另一種則是多行,下面我們用單元 8 的 big() 函數示範單行文件字串的寫法

def big(a, b):
  """回傳較大的參數。"""
  if a > b:
    return a
  else:
    return b

文件字串採用三個引號,也就是字串前後都用三個引號圍起來,單行的文件字串就是簡單的寫明函數用途

"""回傳較大的參數。"""

多行的文件字串同樣用三引號字串 (triple-quoted string) ,如下例

def big(a, b):
  """回傳較大的參數。
    參數:
      a - 第一個參數。
      b - 第二個參數。
  """
  if a > b:
    return a
  else:
    return b

第一行同樣是函數用途,之後空一行,下面才是進一步的解釋說明,此例解釋參數 (parameter) 的用途。有沒有發現三引號字串是可以跨行的呢?是的,三引號字串可以跨行,因為三引號字串的主要用途就是當作文件字串,文件字串通常是多行的敘述。

下面我們替 class_dmeo9.py 加進模組、類別與方法的文件字串

"""Demo 類別的範例。

這個模組示範文件字串的寫法。"""

#類別的註解。
class Demo:
  """類別的文件字串。"""
  
  # __init__() 的註解。
  def __init__(self, v1=11, v2=22):
    """ __init__() 的文件字串。"""
    self.__a = v1
    self.__b = v2
    
  # 方法的註解。
  def do_something(self):
    """方法的文件字串。"""
    return self.__a + self.__b
    
if __name__ == "__main__":
  d = Demo(12, 34)
  print(d.do_something())
    
#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:class_demo10.py
# 功能:示範 Python 中的文件字串
# 作者:張凱慶 */

這裡僅作示範用,因此文件字串中都採取簡單的文字。

我們可以看到模組的文件字串出現在檔案的最開始,類別、方法或函數的文件字串都在關鍵字 (keyword) 的下一行,至於註解則在關鍵字的上一行,除了文件字串的位置須固定外,註解的位置是 Python 社群的習慣寫法,如果要對整個類別、方法或函數做註解,通常都會寫在關鍵字的上一行。

由於文件字串是用途及簡單例子,所以註解內容不應該與文件字串相同或相似,基本上註解的目的主要是對程式碼額外說明,至於說明內容依需要而定。

倒是不管文件字串或是註解都應按照開發團隊的習慣來走,我們這裡介紹的是官網 PEP 8 及 PEP 257 所建議的寫法。

接下來我們開發軟體的方式,帶領讀者開發 GUI 的編密碼軟體,藉此介紹更多的 Python 特性囉!

中英文術語對照
屬性attribute
類別class
註解comment
文件字串documentation string
函數function
關鍵字keyword
串列list
方法method
模組module
物件object
參數parameter
程式語言programming language
原始程式碼source code
三引號字串triple-quoted string
重點整理
1. 文件字串用以說明模組、函數、類別及方法的功能,可用預設屬性 __doc__ 存取。
2. 定義文件字串採用可以跨行的三引號字串,放在模組的開頭或 class 、 def 的下方第一行。
問題與討論
1. 文件字串是什麼?為什麼要在程式中設置文件字串?
2. 什麼是三引號字串?這跟字串有什麼不同?
練習
1. 寫一個程式 exercise1301.py ,替 exercise1201.py 加入文件字串。
2. 寫一個程式 exercise1302.py ,替 exercise1202.py 加入文件字串。
3. 寫一個程式 exercise1303.py ,替 exercise1203.py 加入文件字串。

相關教學影片

上一頁 單元 12 - 模組
回 Python 入門指南首頁
下一頁 軟體開發篇
回 Python 教材首頁
回程式語言教材首頁