Python中的多行注釋文檔編寫風(fēng)格匯總
什么是docstring
在軟件工程中,其實(shí)編碼所占的部分是非常小的,大多是其它的事情,比如寫文檔。文檔是溝通的工具。
在Python中,比較推崇在代碼中寫文檔,代碼即文檔,比較方便,容易維護(hù),直觀,一致。
代碼寫完,文檔也出來了。其實(shí)Markdown也差不多這種思想,文本寫完,排版也完成了。
看看PEP 0257中對docstring的定義:
A docstring is a string literal that occurs as the first statement in
a module, function, class, or method definition. Such a docstring
becomes the __doc__ special attribute of that object.
簡單來說,就是出現(xiàn)在模塊、函數(shù)、類、方法里第一個(gè)語句的,就是docstring。會(huì)自動(dòng)變成屬性__doc__。
def foo(): """ This is function foo"""
可通過foo.__doc__訪問得到' This is function foo'.
各類docstring風(fēng)格:
Epytext
這是曾經(jīng)比較流行的一直類似于javadoc的風(fēng)格。
""" This is a javadoc style. @param param1: this is a first param @param param2: this is a second param @return: this is a description of what is returned @raise keyError: raises an exception """
reST
這是現(xiàn)在流行的一種風(fēng)格,reST風(fēng)格,Sphinx的御用格式。我個(gè)人也是喜歡用這種風(fēng)格,比較緊湊。
""" This is a reST style. :param param1: this is a first param :param param2: this is a second param :returns: this is a description of what is returned :raises keyError: raises an exception """
Google風(fēng)格
""" This is a groups style docs. Parameters: param1 - this is the first param param2 - this is a second param Returns: This is a description of what is returned Raises: KeyError - raises an exception """
Numpydoc (Numpy風(fēng)格)
"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.
Parameters
----------
first : array_like
the 1st param name `first`
second :
the 2nd param
third : {'value', 'other'}, optional
the 3rd param, by default 'value'
Returns
-------
string
a value in a string
Raises
------
KeyError
when a key error
OtherError
when an other error
"""
docstring工具之第三方庫pyment
用來創(chuàng)建和轉(zhuǎn)換docstring.
使用方法就是用pyment生成一個(gè)patch,然后打patch。
$ pyment test.py #生成patch $ patch -p1 < test.py.patch #打patch
詳情:https://github.com/dadadel/pyment
使用sphinx的autodoc自動(dòng)從docstring生產(chǎn)api文檔,不用再手寫一遍
我在代碼中已經(jīng)寫過docstring了,寫api文檔的內(nèi)容跟這個(gè)差不多,難道要一個(gè)一個(gè)拷貝過去rst嗎?當(dāng)然不用。sphinx有autodoc功能。
首先編輯conf.py文件,
1. 要有'sphinx.ext.autodoc'這個(gè)extensions
2. 確保需要自動(dòng)生成文檔的模塊可被import,即在路徑中。比如可能需要sys.path.insert(0, os.path.abspath(‘../..'))
然后,編寫rst文件,
xxx_api module --------------------- .. automodule:: xxx_api :members: :undoc-members: :show-inheritance:
看效果:

相關(guān)文章
Python裝飾器類方法擴(kuò)展元類管理實(shí)例探究
這篇文章主要為大家介紹了Python裝飾器類方法擴(kuò)展元類管理實(shí)例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
Pycharm連接遠(yuǎn)程服務(wù)器并遠(yuǎn)程調(diào)試的全過程
PyCharm 是 JetBrains 開發(fā)的一款 Python 跨平臺(tái)編輯器,下面這篇文章主要介紹了Pycharm連接遠(yuǎn)程服務(wù)器并遠(yuǎn)程調(diào)試的全過程,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2021-06-06
python利用urllib和urllib2訪問http的GET/POST詳解
基于Python實(shí)現(xiàn)評論區(qū)抽獎(jiǎng)功能詳解
python實(shí)現(xiàn)鍵盤輸入的實(shí)操方法

