Python編程的16個壞習(xí)慣
1、手動進行字符串格式化
# 壞習(xí)慣
name = "Alice"
greeting = "Hello, " + name + "!"
# 好習(xí)慣
name = "Alice"
greeting = f"Hello, {name}!"
理由:使用+進行字符串拼接會導(dǎo)致代碼可讀性差,而且在復(fù)雜情況下容易出錯,f-string 可讀性更好
2、手動關(guān)閉文件
# 壞習(xí)慣
file = open("example.txt", "r")
content = file.read()
file.close()
# 好習(xí)慣
with open("example.txt", "r") as file:
content = file.read()
理由:手動關(guān)閉文件容易忘記,使用上下文管理器(with語句)會在代碼執(zhí)行完畢后自動關(guān)閉文件,即使發(fā)生異常也會被正確處理,更加安全可靠
3、使用裸 except子句
# 壞習(xí)慣
try:
result = 10 / 0
except:
print("Error occurred")
# 好習(xí)慣
try:
result = 10 / 0
except ZeroDivisionError:
print("Error occurred")
理由:裸 except 會捕捉所有異常,包括系統(tǒng)退出信號等。這可能會導(dǎo)致在處理異常時掩蓋真正的錯誤,使得調(diào)度變得更加困難。
4、默認參數(shù)使用可變對象
# 壞習(xí)慣
def add_item(item, items=[]):
items.append(item)
return items
# 好習(xí)慣
def add_item(item, items=None):
if items is None:
item = []
items.append(item)
return items
理由:默認參數(shù)在函數(shù)定義時被計算,而不是在每次函數(shù)調(diào)用時。這意味著如果默認參數(shù)是可變對象(如列表或字典),那么它將在所有函數(shù)調(diào)用之間共享,導(dǎo)致意外的結(jié)果
5、不會使用推導(dǎo)式
# 壞習(xí)慣
squares = []
for i in range(5):
squares.append(i ** 2)
# 好習(xí)慣
squares = [i ** 2 for i in range(5)]
理由:推導(dǎo)式是一種簡潔,可讀性高的語法糖,可以減少代碼行數(shù),提高效率
6、使用 type(x) 檢查類型
# 壞習(xí)慣
value = 42
if type(value) is int:
print("It is an integer")
# 好習(xí)慣
value = 42
if isinstance(value, int):
print("It is an integer")
理由:type 不如 isintance 靈活,且無法處理繼承關(guān)系。
7、使用 ==判斷是否為 None, True 或 False
# 壞習(xí)慣
if x == None:
print("x is None")
# 好習(xí)慣
if x is None:
print("x is None")
理由:在Python中, None, True 或 False 是單例對象,使用 is 能確保比較的是對象的身份。另外,對象的 __eq__方法可以被重載,這就意味著 == 可能不總是按照我們的期望的方式進行比較。
8、使用 bool(...) 或 len(...) 進行條件檢查
# 壞習(xí)慣
my_list = [1, 2, 3]
if len(my_list) != 0:
print("List is not empty")
# 好習(xí)慣
my_list = [1, 2, 3]
if my_list:
print("List is not empty")
理由:在條件判斷時使用可讀性更高的表達式,不必顯式地檢查長度或真值。
9、使用 range(len(...)), 而不是 enumerate
# 壞習(xí)慣
my_list = ['apple', 'banana', 'orange']
for i in range(len(my_list)):
item = my_list[i]
print(i, item)
# 好習(xí)慣
my_list = ['apple', 'banana', 'orange']
for i, item in enumerate(my_list):
print(i, item)
理由:enumerate()提供了在迭代中同時獲取索引和值的優(yōu)雅方式,比手動追蹤索引更好
10、不了解字典的 items 方法
# 壞習(xí)慣
my_dict = {'a': 1, 'b': 2, 'c':3}
for key in my_dict:
print(key, my_dict[key])
# 好習(xí)慣
my_dict = {'a': 1, 'b': 2, 'c':3}
for key, value in my_dict.items():
print(key, value)
理由:items() 提供了更直接的方式同時獲取鍵和值,避免了額外的字典查找。
11、不使用元組解包
# 壞習(xí)慣
coordinates = (3, 5)
x = coordinates[0]
y = coordinates[1]
# 好習(xí)慣
coordinates = (3, 5)
x, y = coordinates
理由:元組解包能夠使代碼更加簡潔,提高可讀性。
12、使用 time() 進行代碼計時
# 壞習(xí)慣
start_time = time.time()
end_time = time.time()
# 好習(xí)慣
start_time = time.perf_counter()
end_time = time.perf_counter()
理由:perf_counter()提供了更高精度的計時,適用于測量小段代碼的執(zhí)行時間。time() 通常精度較低,可能不適合測量短時間間隔。
13、在生產(chǎn)環(huán)境使用 print 語句而不是日志
# 壞習(xí)慣
result = calculate_result()
print("Result:", result)
# 好習(xí)慣
import logging
result = calculate_result()
logging.info("Result: %s", result)
理由:print 語句是調(diào)度的一種方式,但在生產(chǎn)環(huán)境中使用日志更為合適,具備更多配置選項和級別
14、使用 import * 導(dǎo)入模塊
# 壞習(xí)慣
from module import *
# 好習(xí)慣
from module import specific_function_or_class
理由:導(dǎo)入所有符號可能導(dǎo)致命名沖突,不利用代碼維護。
15、不使用原始字符串
# 壞習(xí)慣
regular_string = "C:\\Documnets\\file.txt"
# 好習(xí)慣
regular_string = r"C:\Document\file.txt"
理由:使用原始字符串可以提高代碼的可讀性,尤其是在處理路徑,正則表達式等需要反斜杠的情況下。原始字符串告訴讀者不要解釋反斜杠為轉(zhuǎn)義字符。
16、不遵循 PEP8 編碼規(guī)范
# 壞習(xí)慣
aVar=5
result=aVar+2
# 好習(xí)慣
a_var = 5
result = a_var + 2
理由:PEP8 提供了一致的代碼風(fēng)格,有助于提高代碼的可讀性,可維護性,以及團隊協(xié)作。
本文來自博客園,作者:業(yè)余磚家,轉(zhuǎn)載請注明原文鏈接:http://www.rzrgm.cn/yeyuzhuanjia/p/18334254

浙公網(wǎng)安備 33010602011771號