python 文件字串 docstrings 用法規範
阿新 • • 發佈:2018-11-25
文件字串用來描述函式、類和方法。它是一個重要的工具,不僅使程式更加簡潔易懂,而且還方便程式的編寫。一對引號之間的內容是字串,三對引號之間的內容是文件字串。下面是一個簡單的例子:
def add(x, y):
"""
引號裡的內容是文件字串.
這個函式接受兩個引數,將它們相加並返回
"""
result = x + y
return result
我們可以通過 function_name.__doc__ 的方式檢視函式的文件字串:
>>> add.__doc__ 引號裡的內容是文件字串. 這個函式接受兩個引數,將它們相加並返回
類似於python有它的編寫規範,docstrings也有它的編寫規範。不遵守規範雖然不會影響程式碼的執行,但是不利於別人閱讀你的程式碼。我們可以檢視幾個python內建函式的docstrings:
>>> print(max.__doc__) max(iterable, *[, default=obj, key=func]) -> value max(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument. >>> print(print.__doc__) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
可以看出,規範的文件字串分兩個部分,中間用一個空行隔開。第一部分描述函式的引數(注意位置引數和關鍵字引數的表示方式)、是否返回值(有無 -> value);第二部分說明函式的用法,如果引數有很多,還需要說明各引數的含義。
回到開始時的例子,規範的文件字串如下:
def add(x, y):
"""
add(x, y) -> value
返回兩個引數的和
"""
result = x + y
return result
使用規範的文件字串的另一個好處:在有自動補全的IDE中,輸入函式名和括號,該函式的所有引數都將出現在括號中。在呼叫函式的時候,就不用跑到函式定義的地方去看引數的位置和關鍵字,可以省時間。
把文件字串打印出來,會看到很有意思的事:
>>> """one
... two
... three"""
'one\ntwo\nthree'