前言
成功的法則極為簡單,但簡單並不代表容易。
一、代碼注釋介紹
- 注釋就是對代碼的解釋和說明,其目的是讓人們能夠更加輕松地了解代碼。
- 注釋是編寫程序時,寫程序的人給一個語句、程序段、函數等的解釋或提示,能提高程序代碼的可讀性。
- 在有處理邏輯的代碼中,源程序有效注釋量必須在20%以上。
二、代碼注釋分類
- 行注釋:在符號后那一行不會被編譯(顯示)
- 塊注釋:被塊注釋符號中間的部分不會被編譯
三、python代碼注釋基礎
- Python中使用#表示單行注釋。單行注釋可以作為單獨的一行放在被注釋代碼行之上,也可以放在語句或表達式之后。如下例子:
name = 'xiaohong' # 單行注釋
# 單行注釋
name = 'xiaohong'
- Python中使用三個單引號或三個雙引號表示多行注釋。用在注釋多寫不下的情況,如下例子:
'''
這是使用三個單引號的多行注釋
'''
"""
這是使用三個雙引號的多行注釋
"""
四、DocStrings介紹與使用
4.1 DocStrings介紹
文檔字符串
是一個重要工具,用於解釋文檔程序,幫助你的程序文檔更加簡單易懂
4.2 python中使用DocStrings
在函數體的第一行使用一對三個單引號 ''' 或者一對三個雙引號 """ 來定義文檔字符串。你可以使用 doc(注意雙下划線)調用函數中的文檔字符串屬性。
編寫示例如下:
def add(num1,num2):
""" 完成傳入的兩個數之和
:param num1: 加數1
:param num2: 加數2
:return: 和
"""
return num1 + num2
print( add.__doc__ )
備注:DocStrings 文檔字符串使用慣例:它的首行簡述函數功能,第二行空行,第三行為函數的具體描述。
五、DocStrings常用編寫風格
5.1 reST風格
這是現在流行的一種風格,reST風格,Sphinx的御用格式,比較緊湊。
"""
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
"""
5.2 Google風格
"""
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
"""
5.3 Numpydoc (Numpy風格)
"""
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
"""
六、一些注釋經驗
- 注釋不是越多越好。對於一目了然的代碼,不需要添加注釋。
- 對於復雜的操作,應該在操作開始前寫上相應的注釋。
- 對於不是一目了然的代碼,應該在代碼之后添加注釋。
- 絕對不要描述代碼。一般閱讀代碼的人都了解Python的語法,只是不知道代碼要干什么