1. 程式人生 > >編寫Python程式碼的幾條建議,學以致用!

編寫Python程式碼的幾條建議,學以致用!

編寫Python程式碼的幾條建議,學以致用!

1.Mutable and immutable types

Python有兩種內建或使用者定義的型別。

  • 可變型別是允許就地修改內容的型別。典型的可變列表是列表和詞典:所有列表都有變異方法,如 list.append()或list.pop(),並且可以在適當的位置進行修改。詞典也是如此。
  • 不可變型別不提供改變其內容的方法。例如,設定為整數6的變數x沒有“增量”方法。如果要計算x + 1,則必須建立另一個整數併為其指定名稱。

編寫Python程式碼的幾條建議,學以致用!

體會一下這Best這招,選擇是使用map函式,它可以將內建函式型別str對映到迭代器range。這會生成一個map物件,然後就可以像其他示例一樣join。在某些情況下,map函式甚至可能比列表理解更快,更簡潔!

2.One statement per line

每一行一個語句,尤其在複雜的邏輯表示式的時候,這樣會清晰很容易閱讀。

編寫Python程式碼的幾條建議,學以致用!

雖然列表推導等一些複合語句因其簡潔性和表達性而被允許和讚賞,但在同一行程式碼上有兩個脫節語句是不好的做法

3.Explicit code

Python因為技巧性非常高,有的時候濫用一些黑魔法,過度的使用技巧而反而失去了程式碼本身的直觀性。

編寫Python程式碼的幾條建議,學以致用!

字典的更新有幾種方法,dict(locals)本意是想生成一個新的字典返回。在上面的好程式碼中,顯式地從呼叫者接收x和y,並返回顯式字典。使用此函式的開發人員通過讀取第一行和最後一行

就能確切地知道要做什麼**,而不是像壞例子的那種情況,比較晦澀難懂,不直接。

4.Returning values

關於返回值的處理

當函式的複雜性增加時,在函式體內使用多個return語句並不罕見。但是,為了保持清晰的意圖和可持續的可讀性水平,最好避免從體內的許多輸出點返回有意義的值。

在函式中返回值有兩種主要情況:函式在正常處理時返回的結果,以及指示錯誤輸入引數的錯誤情況或函式無法完成其計算的任何其他原因或任務

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">def complex_function(a, b, c):
if not a:
return None # Raising an exception might be better
if not b:
return None # Raising an exception might be better

Some complex code trying to compute x from a, b and c

Resist temptation to return x if succeeded

if not x:

Some Plan-B computation of x

return x # One single exit point for the returned value x will help

when maintaining the code.

</pre>

(程式碼可以左右滑動)

當一個函式在其正常過程中有多個主要出口時,除錯返回的結果變得很困難,因此最好保留一個退出點。這也將有助於分解一些程式碼路徑,如果函式有多個出口點,說明你的程式碼要進一步的重構。

5.Unpacking

如果知道列表或元組的長度,則可以通過解壓縮為其元素指定名稱。比如enumerate()將為列表中的每個項提供兩個元素的元組,一個下標一個值:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">for index, item in enumerate(some_list):

do something with index and item

</pre>

也可以使用它來交換變數:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">a, b = b, a
</pre>

巢狀解包也適用Py3.x:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">a, (b, c) = 1, (2, 3)
a, *rest = [1, 2, 3]

a = 1, rest = [2, 3]

a, *middle, c = [1, 2, 3, 4]

a = 1, middle = [2, 3], c = 4

</pre>

6.Searching for an item in a collection

有時我們需要搜尋一系列的東西。讓我們看看兩個選項:列表和集合。

以下面的程式碼為例:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">s = set(['s', 'p', 'a', 'm'])
l = ['s', 'p', 'a', 'm']
def lookup_set(s):
return 's' in s
def lookup_list(l):
return 's' in l
</pre>

  • 即使兩個函式看起來都相同,因為lookup_set利用了Python中的集合是雜湊表的事實,兩者之間的查詢效能是非常不同的。
  • 要確定專案是否在列表中,Python必須遍歷每個專案,直到找到匹配的專案。
  • 這很費時,特別是對於長列表。另一方面,在集合中專案的雜湊將告訴Python在集合中的哪個位置尋找匹配專案。因此,即使集合很大,也可以快速完成搜尋

7.Check if variable equals a constan

檢查變數是否等於常數

您不需要顯式地將值與True或None或空進行比較 - 您只需將其新增到if語句即可。

編寫Python程式碼的幾條建議,學以致用!

8.Access a Dictionary Element

訪問字典元素

不要使用該dict.has_key()方法。相反使用語法或傳遞預設引數 比如x in dict ,dict.get(k,default_value)

編寫Python程式碼的幾條建議,學以致用!

9.Filtering a list

過濾列表壞的做法,或者初學者經常會犯的錯誤

編寫Python程式碼的幾條建議,學以致用!

好的做法是使用filter函式,從Python 3.0開始,該filter()函式返回迭代器而不是列表。如果你真的需要一個列表,前面加一個list()即可!

10.Read From a File

使用語法從檔案中讀取,這將自動為您關閉檔案,一定要用with open

編寫Python程式碼的幾條建議,學以致用!

11.Line Continuations

程式碼長度的持續

  • 當我們的邏輯程式碼行長於可接受的限制時(PEP8規定是79個字元),需要將其拆分為多個物理行。
  • 如果行的最後一個字元是反斜槓,Python直譯器將連線連續的行。這在某些情況下很有用,但通常應該避免因為它的脆弱性。
  • 在反斜槓之後新增到行尾的空格會破壞程式碼並可能產生意外結果。

Bad:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">my_very_big_string = """For a long time I used to go to bed early. Sometimes,
when I had put out my candle, my eyes would close so quickly that I had not even
time to say “I’m going to sleep.”"""
from some.deep.module.inside.a.module import a_nice_function, another_nice_function,
yet_another_nice_function
</pre>

Good:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">my_very_big_string = (
"For a long time I used to go to bed early. Sometimes, "
"when I had put out my candle, my eyes would close so quickly "
"that I had not even time to say “I’m going to sleep.”"
)
from some.deep.module.inside.a.module import (
a_nice_function, another_nice_function, yet_another_nice_function)
</pre>

更好的做法是在元素周圍使用括號。在行尾留下一個未閉合的括號,Python直譯器將加入下一行,直到括號被關閉。對於大括號和方括號,同樣的行為也適用。在這裡呢,小編也準備了一份Python入門學習資料,加小編QQ群:700341555即可免費領取!