簡潔概述
1、編碼
如無特殊情況, 文件一律使用UTF-8 編碼
如無特殊情況, 檔案頭部必須加入#-*-coding:utf-8-*-標識
2、程式碼格式
2.1、縮排
統一使用4 個空格進行縮排
2.2、行寬
每行程式碼盡量不超過80 個字元(在特殊情況下可以略微超過80 ,但最長不得超過120)
原因:
這在查看side-by-side 的diff 時很有幫助
方便在控制台下方查看程式碼
太長可能是設計有缺陷
2.3、引號
簡單說,自然語言使用雙引號,機器標示使用單引號,因此代碼裡多數應該使用單引號
#2.4、空白行
class A: def __init__(self): pass def hello(self): pass def main(): pass
2.5、編碼
#3、import 語句
import 語句應該分行書寫#
# 正确的写法 import os import sys # 不推荐的写法 import sys,os # 正确的写法 from subprocess import Popen, PIPE import语句应该使用 absolute import # 正确的写法 from foo.bar import Bar # 不推荐的写法 from ..bar import Bar
import os import sys import msgpack import zmq import foo
from myclass import MyClass
import bar import foo.bar bar.Bar() foo.bar.Bar()
4、空格
# 正确的写法 i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) # 不推荐的写法 i=i+1 submitted +=1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b)
# 正确的写法 def complex(real, imag): pass # 不推荐的写法 def complex(real,imag): pass
函數的參數清單中,預設值等號兩邊不要添加空格
# 正确的写法 def complex(real, imag=0.0): pass # 不推荐的写法 def complex(real, imag = 0.0): pass
左括號之後,右括號之前不要加多餘的空格
# 正确的写法 spam(ham[1], {eggs: 2}) # 不推荐的写法 spam( ham[1], { eggs : 2 } )
#字典物件的左括號之前不要多餘的空格
# 正确的写法 dict['key'] = list[index] # 不推荐的写法 dict ['key'] = list [index]
不要為對齊賦值語句而使用的額外空格
# 正确的写法 x = 1 y = 2 long_variable = 3 # 不推荐的写法 x = 1 y = 2 long_variable = 3
5、換行
Python 支援括號內的換行。這時有兩種情況。
1.第二行縮排到括號的起始處
foo = long_function_name(var_one, var_two, var_three, var_four)
2.第二行縮排4 個空格,適用於起始括號就換行的情形
def long_function_name( var_one, var_two, var_three, var_four): print(var_one)
使用反斜線\換行,二元運算子.等應出現在行末;長字串也可以用此法換行
session.query(MyTable).\ filter_by(id=1).\ one() print 'Hello, '\ '%s %s!' %\ ('Harry', 'Potter')
禁止複合語句,即一行中包含多個語句:
# 正确的写法 do_first() do_second() do_third() # 不推荐的写法 do_first();do_second();do_third();
if/for/while一定要換行:
# 正确的写法 if foo == 'blah': do_blah_thing() # 不推荐的写法 if foo == 'blah': do_blash_thing()
#6、docstring
docstring 的規範中最其本的兩點:
1.所有的公共模組、函數、類別、方法,都應該寫docstring 。私有方法不一定需要,但應該在 def 之後提供一個區塊註解來說明。
2.docstring 的結束"""應該獨佔一行,除非此 docstring 只有一行。
"""Return a foobar Optional plotz says to frobnicate the bizbaz first. """ """Oneline docstring"""下一節