python代碼規(guī)范 本規(guī)范基于Python社區(qū)官方代碼風(fēng)格文檔PEP-0008 基本格式 縮進
空格
行寬 每行代碼盡量不超過80個字符 理由:
換行 Python支持括號內(nèi)的換行,。這時有兩種情況: 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) 使用反斜杠\換行,二元運算符+,、 .等應(yīng)出現(xiàn)在行首,,并與上一行的.或=對齊,;或者縮進4個空格。長字符串也可以用此法換行 foo = variable_with_long_name \ + another_variable \ + variable session.query(MyTable) \ .filter_by(id=1) \ .one() this_is_a_very_long(function_call, 'with many parameters') \ .that_returns_an_object_with_an_attribute print 'Hello, ' \ '%s %s!' % \ ('Harry', 'Potter') 多個元素的list或者tuple,,在起始括號后換行,,第二行縮進4個空格 items = [ 'this is the first', 'set of items', 'with more items', 'to come in this line', 'like this' ] 禁止復(fù)合語句,即一行中包含多個語句: # yes do_first() do_second() do_third() # no do_first();do_second();do_third(); if/for/while一定要換行: # yes if foo == 'blah': do_blah_thing() # no if foo == 'blah': do_blash_thing() 空行
class A: '''This is a simple docstring.''' def __init__(self): passdef hello(self): passdef hello(name): print 'Hello %s!' % name def main(): pass
表達式 空格
# yes exp = -1.05 i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) # no exp = - 1.05 i=i+1 submitted +=1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b)
# yes def complex(real, imag): pass # no def complex(real,imag): pass
# yes def complex(real, imag=0.0): pass # no def complex(real, imag = 0.0): pass
# yes spam(ham[1], {eggs: 2}) value = my_list[index] # no spam( ham[1], { eggs : 2 } ) value = my_list[ index ]
# yes dict['key'] = list[index] # no dict ['key'] = list [index]
# yes x = 1 y = 2 long_variable = 3 # no x = 1 y = 2 long_variable = 3 比較
# yes if method == 'md5': passif not foo: passif foo not in bar: passif instance(a, C): pass # no if 'md5' == method: passif foo == False: passif not foo in bar: passif type(A) is C: pass 引號 簡單說,自然語言使用雙引號,,機器標示使用單引號,,因此 代碼里 多數(shù)應(yīng)該使用 單引號
import語句
# yes import os import sys # no import sys,os # yes from subprocess import Popen, PIPE
# yes from foo.bar import Bar # no from ..bar import Bar
import osimport sys import msgpackimport zmq import foo
from myclass import MyClass
import bar import foo.bar bar.Bar() foo.bar.Bar() 注釋 文件頭部注釋 在文件頭部指明文件編碼格式及開發(fā)者 # -*- coding: utf-8 -*- ''' Author: Li Lei Date: 2016-05-01 ''' 塊注釋 #號后空一格,,段落間用空行分開(同樣需要#號) # 塊注釋# 塊注釋## 塊注釋# 塊注釋 行注釋 至少使用兩個空格和語句分開,使用有意義的注釋 # yes x = x + 1 # 邊框加粗一個像素 # no x = x + 1 # x加1 docstring docstring的規(guī)范在 PEP 257 中有詳細描述,,其中最其本的兩點:
'''Return a foobarOptional plotz says to frobnicate the bizbaz first.''''''Oneline docstring''' 命名規(guī)范
MAX_OVERFLOW = 100 Class FooBar: def foo_bar(self, print_): print(print_) 函數(shù)和方法的參數(shù)變量命名:
編碼
|
|