注釋
注釋
1、注釋
1.1、塊注釋
“#”號后空一格,段落件用空行分開(同樣需要“#”號)
# 塊注釋 # 塊注釋 # # 塊注釋 # 塊注釋
1.2、行注釋
至少使用兩個空格和語句分開,注意不要使用無意義的注釋
# 正確的寫法 x = x + 1 # 邊框加粗一個像素 # 不推薦的寫法(無意義的注釋) x = x + 1 # x加1
1.3、建議
在代碼的關鍵部分(或比較復雜的地方), 能寫注釋的要盡量寫注釋
比較重要的注釋段, 使用多個等號隔開, 可以更加醒目, 突出重要性
app = create_app(name, options) # ===================================== # 請勿在此處添加 get post等app路由行為 !!! # ===================================== if __name__ == '__main__': app.run()
2、文檔注釋(Docstring)
作為文檔的Docstring一般出現(xiàn)在模塊頭部、函數(shù)和類的頭部,這樣在python中可以通過對象的__doc__對象獲取文檔. 編輯器和IDE也可以根據(jù)Docstring給出自動提示.
文檔注釋以 """ 開頭和結尾, 首行不換行, 如有多行, 末行必需換行, 以下是Google的docstring風格示例
# -*- coding: utf-8 -*- """Example docstrings. This module demonstrates documentation as specified by the `Google Python Style Guide`_. Docstrings may extend over multiple lines. Sections are created with a section header and a colon followed by a block of indented text. Example: Examples can be given using either the ``Example`` or ``Examples`` sections. Sections support any reStructuredText formatting, including literal blocks:: $ python example_google.py Section breaks are created by resuming unindented text. Section breaks are also implicitly created anytime a new section starts. """
不要在文檔注釋復制函數(shù)定義原型, 而是具體描述其具體內(nèi)容, 解釋具體參數(shù)和返回值等
# 不推薦的寫法(不要寫函數(shù)原型等廢話) def function(a, b): """function(a, b) -> list""" ... ... # 正確的寫法 def function(a, b): """計算并返回a到b范圍內(nèi)數(shù)據(jù)的平均值""" ... ...
對函數(shù)參數(shù)、返回值等的說明采用numpy標準, 如下所示
def func(arg1, arg2): """在這里寫函數(shù)的一句話總結(如: 計算平均值). 這里是具體描述. 參數(shù) ---------- arg1 : int arg1的具體描述 arg2 : int arg2的具體描述 返回值 ------- int 返回值的具體描述 參看 -------- otherfunc : 其它關聯(lián)函數(shù)等... 示例 -------- 示例使用doctest格式, 在`>>>`后的代碼可以被文檔測試工具作為測試用例自動運行 >>> a=[1,2,3] >>> print [x + 3 for x in a] [4, 5, 6] """
文檔注釋不限于中英文, 但不要中英文混用
文檔注釋不是越長越好, 通常一兩句話能把情況說清楚即可
模塊、公有類、公有方法, 能寫文檔注釋的, 應該盡量寫文檔注釋