Python基础概念_12_编程风格
編程風格
13?編程風格
13.1?簡介
為了編程的規范,我們一般約定一些編程規則、約定,這些都稱為編程風格。
13.2?分號
不要在行尾加分號, 也不要用分號將兩條命令放在同一行。
13.3?行長度
1)??????每行不超過80個字符。當然也有例外的情況,比如:
長的導入模塊語句或者注釋里的URL
2)??????不要使用反斜杠連接行.
Python會將?圓括號,中括號和花括號中的行隱式的連接起來?, 你可以利用這個特點. 如果需要, 你可以在表達式外圍增加一對額外的圓括號.
foo_bar(self, width, height, color='black',design=None, x='foo',
????????????emphasis=None, highlight=0)
???? if (width== 0 and height == 0 and
???????? color== 'red' and emphasis == 'strong'):
3)??????如果一個文本字符串在一行放不下, 可以使用圓括號來實現隱式行連接:
x = ('This will build a very long long '
???? 'long longlong long long long string')
4)??????在注釋中,如果必要,將長的URL放在一行上。
#http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
13.4?括號
除非是用于實現行連接, 否則不要在返回語句或條件語句中使用括號. 不過在元組兩邊使用括號是可以的。
推薦的代碼風格:
if foo:
???????? bar()
???? while x:
???????? x =bar()
???? if x and y:
???????? bar()
???? if not x:
???????? bar()
???? return foo
???? for (x, y)in dict.items(): ...
不建議的代碼風格:?
if (x):
???????? bar()
???? if not(x):
???????? bar()
???? return (foo)
13.5?應用
用4個空格來或則tab來縮進代碼絕不能tab和空格混用。
13.6?空格
按照標準的排版規范來使用標點兩邊的空格。
1)??????括號內不要有空格.
推薦方式:
spam(ham[1], {eggs: 2}, [])
不建議方式:?
spam( ham[ 1 ], { eggs: 2 }, [ ] )
2)??????不要在逗號, 分號, 冒號前面加空格, 但應該在它們后面加(除了在行尾).
推薦方式:
if x == 4:
???????? printx, y
???? x, y = y, x
不建議方式:?
if x == 4 :
???????? print x, y
???? x , y = y ,x
3)??????參數列表, 索引或切片的左括號前不應加空格.
推薦方式:
spam(1)
不推薦:
spam (1)
推薦方式:
dict['key'] = list[index]
不推薦方式:?
dict ['key'] = list [index]
4)??????在二元操作符兩邊都加上一個空格, 比如賦值(=), 比較(==,<, >, !=, <>, <=, >=, in, not in, is, is not), 布爾(and, or, not). 至于算術操作符兩邊的空格該如何使用, 需要你自己好好判斷. 不過兩側務必要保持一致.
建議方式:
x == 1
不建議:
? x<1
5)??????當'= '用于指示關鍵字參數或默認參數值時, 不要在其兩側使用空格.
推薦方式:
def complex(real, imag=0.0): return magic(r=real,i=imag)
不建議方式:?
def complex(real, imag = 0.0): return magic(r = real,i = imag)
6)??????不要用空格來垂直對齊多行間的標記, 因為這會成為維護的負擔(適用于:,#, =等):
推薦方式:
???? foo =1000? # comment
???? long_name =2? # comment that should not be aligned
???? dictionary= {
????????"foo": 1,
????????"long_name": 2,
???????? }
不建議方式:
???? foo?????? = 1000?# comment
???? long_name =2???? # comment that should not bealigned
???? dictionary= {
????????"foo"????? : 1,
????????"long_name": 2,
???????? }
13.7?注釋
1)??????文檔字符串
一般使用'''或則 """來實現文檔字符串。?文檔字符串是我們使用Python過程中一個很重要的工具,他對程序文檔很有幫助,使程序很容易理解。甚至當程序運行的時候,我們可以從一個函數中返回文檔字符串。
2)??????函數和方法
下文所指的函數,包括函數, 方法, 以及生成器。一個函數必須要有文檔字符串, 除非它外部不可見或者非常短小或者簡單明了。
一般我們在函數或者方法里按照Args(參數)、Returns(返回)、Raises(異常拋出)3個方面聲明文檔字符串。詳細解釋見下:
Args:
列出每個參數的名字, 并在名字后使用一個冒號和一個空格, 分隔對該參數的描述.如果描述太長超過了單行80字符,使用2或者4個空格的懸掛縮進(與文件其他部分保持一致). 描述應該包括所需的類型和含義. 如果一個函數接受*foo(可變長度參數列表)或者**bar(任意關鍵字參數), 應該詳細列出*foo和**bar.
Returns: (或者 Yields: 用于生成器)
描述返回值的類型和語義. 如果函數返回None, 這一部分可以省略.
Raises:
列出與接口有關的所有異常.
?
注釋代碼樣例:
?
"""
def fetch_bigtable_rows(big_table, keys,other_silly_variable=None):
??? Fetches rowsfrom a Bigtable.
??? Retrievesrows pertaining to the given keys from the Table instance
??? representedby big_table.? Silly things may happen if
???other_silly_variable is not None.
??? Args:
??????? big_table:An open Bigtable Table instance.
??????? keys: Asequence of strings representing the key of each table row
??????????? tofetch.
???????other_silly_variable: Another optional variable, that has a much
???????????longer name than the other args, and which does nothing.
??? Returns:
??????? A dictmapping keys to the corresponding table row data
??????? fetched.Each row is represented as a tuple of strings.
For example:
???????{'Serak': ('Rigel VII', 'Preparer'),
???????? 'Zim':('Irk', 'Invader'),
???????? 'Lrrr':('Omicron Persei 8', 'Emperor')}
??????? If a keyfrom the keys argument is missing from the dictionary,
??????? thenthat row was not found in the table.
??? Raises:
??????? IOError:An error occurred accessing the bigtable.Table object.
??? """
??? pass
3)??????塊注釋和行注釋
最需要寫注釋的是代碼中那些技巧性的部分,應該在實現前寫上若干行注釋. 對于那些不是一目了然的代碼, 應在其行尾添加注釋說明。
# We use a weighted dictionary search to find outwhere i is in
# the array.? Weextrapolate position based on the largest num
# in the array and the array size and then do binarysearch to
# get the exact number.
if i & (i-1) == 0:??????? # true iff i is a power of 2
4)??????為了提高可讀性, 注釋應該至少離開代碼2個空格.
5) ?注釋里不需要加代碼實現的詳細描述性的信息,可適當描述實現過程和功能。
# 不建議的注釋: COMMENT: Now go through the b array and make sure whenever i occurs
# the next element is i+1
13.8?命名
1)??????應該避免的名稱
a) 單字符名稱, 除了計數器和迭代器.
b) 包/模塊名中的連字符(-)
c) 雙下劃線開頭并結尾的名稱(Python保留, 例如__init__)
2)??????命名約定
a)????????所謂”內部(Internal)”表示僅模塊內可用, 或者, 在類內是保護或私有的.
b)????????用單下劃線(_)開頭表示模塊變量或函數是protected的(使用import * from時不會包含).
c)????????用雙下劃線(__)開頭的實例變量或方法表示類內私有.
d)????????將相關的類和頂級函數放在同一個模塊里. 不像Java, 沒必要限制一個類一個模塊.
e)????????對類名使用大寫字母開頭的單詞(如CapWords, 即Pascal風格), 但是模塊名應該用小寫加下劃線的方式(如lower_with_under.py). 盡管已經有很多現存的模塊使用類似于CapWords.py這樣的命名, 但現在已經不鼓勵這樣做, 因為如果模塊名碰巧和類名一致, 這會讓人困擾.
3)??????Python之父Guido推薦的風格
| 類型 | 公用的 | 內部的 |
| Modules | lower_with_under | _lower_with_under |
| Packages | lower_with_under | |
| Classes | CapWords | _CapWords |
| Exceptions | CapWords | |
| Functions | lower_with_under() | _lower_with_under() |
| Global/Class Constants | CAPS_WITH_UNDER | _CAPS_WITH_UNDER |
| Global/Class Variables | lower_with_under | _lower_with_under |
| Instance Variables | lower_with_under | _lower_with_under (protected) or __lower_with_under (private) |
| Method Names | lower_with_under() | _lower_with_under() (protected) or __lower_with_under() (private) |
| Function/Method Parameters | lower_with_under | |
| Local Variables | lower_with_under |
13.9?導入格式
1)??????每個導入應該獨占一行。
推薦方式:
import os
import sys
不建議方式:?
import os, sys
2)??????導入總應該放在文件頂部, 位于模塊注釋和文檔字符串之后, 模塊全局變量和常量之前. 導入應該按照從最通用到最不通用的順序分組:
標準庫導入、
第三方庫導入、
應用程序指定導入
3)??????每種分組中, 應該根據每個模塊的完整包路徑按字典序排序, 忽略大小寫.
導入示例:
import foo
from foo import bar
from foo.bar import baz
from foo.bar import Quux
from Foob import ar
13.10?總結
本章我們學習如何優雅的進行python編程,接下來我們一起熟悉下Python里的常用關鍵字.
總結
以上是生活随笔為你收集整理的Python基础概念_12_编程风格的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 建设银行信用卡年费标准
- 下一篇: websocket python爬虫_p