二、註釋
1. 塊註釋
“#”號後空一格,段落件用空行分開(同樣需要“#”號)
# 塊註釋
# 塊註釋
#
# 塊註釋
# 塊註釋
2. 行註釋
至少使用兩個空格和語句分開,注意不要使用無意義的註釋
# 正確的寫法
x = x + 1 # 邊框加粗一個像素
# 不推薦的寫法(無意義的註釋)
x = x + 1 # x加1
3. 建議
- 在代碼的關鍵部分(或比較複雜的地方), 能寫註釋的要儘量寫註釋
- 比較重要的註釋段, 使用多個等號隔開, 可以更加醒目, 突出重要性
app = create_app(name, options)
# =====================================
# 請勿在此處添加 get post等app路由行爲 !!!
# =====================================
if __name__ == '__main__':
app.run()
4. 文檔註釋(Docstring)
作爲文檔的Docstring一般出現在模塊頭部、函數和類的頭部,這樣在python中可以通過對象的__doc__對象獲取文檔. 編輯器和IDE也可以根據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.
"""
- 不要在文檔註釋複製函數定義原型, 而是具體描述其具體內容, 解釋具體參數和返回值等
# 不推薦的寫法(不要寫函數原型等廢話)
def function(a, b):
"""function(a, b) -> list"""
... ...
# 正確的寫法
def function(a, b):
"""計算並返回a到b範圍內數據的平均值"""
... ...
- 對函數參數、返回值等的說明採用numpy標準, 如下所示
def func(arg1, arg2):
"""在這裏寫函數的一句話總結(如: 計算平均值).
這裏是具體描述.
參數
----------
arg1 : int
arg1的具體描述
arg2 : int
arg2的具體描述
返回值
-------
int
返回值的具體描述
參看
--------
otherfunc : 其它關聯函數等...
示例
--------
示例使用doctest格式, 在`>>>`後的代碼可以被文檔測試工具作爲測試用例自動運行
>>> a=[1,2,3]
>>> print [x + 3 for x in a]
[4, 5, 6]
"""
- 文檔註釋不限於中英文, 但不要中英文混用
- 文檔註釋不是越長越好, 通常一兩句話能把情況說清楚即可
- 模塊、公有類、公有方法, 能寫文檔註釋的, 應該儘量寫文檔註釋