#Python
一些 Python 的奇技淫巧
0 views
引入
提到 Python,多數人會先想到它「簡潔易讀」的語法、「萬物皆物件」 的設計,或是在資料分析、爬蟲、AI 領域裡開箱即用的豐富函式庫。但很少有人注意到,這門語言還藏著許多「不走尋常路」的巧思。
(疊個甲,我在澳門 Python 解難大賽拿過冠軍)
1. 海象運算子 (:=)
海象運算子允許你在運算式中進行賦值,簡化重複計算或賦值。
python
if (data := get_data()) is not None: # 賦值並檢查
process(data)
2. 實作泛型函數
functools 中的 singledispatch 允許根據第一個參數的型態來分派不同的函數實作。
python
from functools import singledispatch
@singledispatch
def better_print(obj):
return f"Unknown type: {obj}"
@better_print.register
def _(obj: int):
return f"Integer: {obj}"
@better_print.register
def _(obj: list):
return f"List with {len(obj)} items: {obj}"
print(better_print(10)) # 輸出:Integer: 10
print(better_print([1,2])) # 輸出:List with 2 items: [1, 2]
print(better_print("hi")) # 輸出:Unknown type: hi
3. 使用 ...(Ellipsis) 作為預留位置
python
def unfinished_function():
... # TODO: 實作這個函數
4. 解包
- 合併字典 / 列表:
python
dict1 = {"a": 1}
dict2 = {"b": 2}
merged = {**dict1, **dict2}
print(merged) # 輸出:{'a': 1, 'b': 2}
- 提出元素
python
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 輸出:1
print(middle) # 輸出:[2, 3, 4]
print(last) # 輸出:5
- 拆解列表 / 元組作為位置參數
python
def add(a, b, c):
return a + b + c
nums = [1, 2, 3]
print(add(*nums)) # 輸出:6
- 拆解字典作為關鍵字參數
python
params = {"a": 10, "b": 20, "c": 30}
print(add(**params)) # 輸出:60
5. 利用 slots 優化記憶體使用
預設情況下,Python 類別的實例使用字典 (__dict__) 來儲存屬性,這提供了靈活性但消耗較多記憶體。 __slots__ 允許你預先宣告實例擁有的屬性名稱,避免建立 __dict__,從而顯著減少記憶體開銷。
python
class Point:
__slots__ = ("x", "y") # 只允許有 x 和 y 屬性
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
p.z = 5 # AttributeError
6. 利用字典的 missing 方法實作自動鍵值生成
當存取字典中不存在的鍵時,除了用 get() 或 setdefault(),你還可以自訂一個類別,覆寫 __missing__ 方法來動態生成預設值。
python
class AutoVivifyDict(dict):
def __missing__(self, key):
# 當 key 不存在時,自動建立一個新的空字典作為值
new_dict = {}
self[key] = new_dict
return new_dict
data = AutoVivifyDict()
data["a"]["b"] = 42
print(data) # 輸出:{'a': {'b': 42}}
7. 鏈式比較
python
x = 5
if 0 < x < 10: # 等價 x > 0 and x < 10
print("x is between 0 and 10")
結語
善用這些技巧,可以讓你的 Python 程式碼更加優雅、高效;濫用它們,則可能創造出難以維護的「屎山」。
希望這篇文章能給你帶來啟發!