Python 物件複製分為「淺拷貝」與「深拷貝」,差異在於是否遞迴複製嵌套的可變物件。本文用圖解與程式碼實驗徹底釐清兩者行為差異、記憶體結構與常見坑點。
| 拷貝類型 | 建立新物件 | 嵌套可變物件 | 模組函數 |
|---|---|---|---|
| 淺拷貝 | 是 | 共享引用 (同一記憶體) | copy.copy(), list[:], list(), dict.copy() |
| 深拷貝 | 是 | 遞迴建立新物件 | copy.deepcopy() |
>> import copy
>>> person = ['name', ['savings', 100]]
>>> hubby = person[:] # 淺拷貝
>>> wifey = list(person) # 淺拷貝
>>> id(person), id(hubby), id(wifey)
(140123..., 140124..., 140125...) # 外層列表不同物件
# 內層列表 id 相同 → 共享引用
>>> [id(x) for x in person], [id(x) for x in hubby], [id(x) for x in wifey]
[[140126..., 140127...], [140126..., 140127...], [140126..., 140127...]]
# 修改不可變元素 (字串) → 建立新字串,不影響其他
>>> hubby[0] = 'joe'
>>> wifey[0] = 'jane'
>>> person, hubby, wifey
(['name', ['savings', 100]], ['joe', ['savings', 100]], ['jane', ['savings', 100]])
# 修改可變嵌套元素 (列表) → 原地修改,三者同步變化!
>>> hubby[1][1] = 70
>>> person, hubby, wifey
(['name', ['savings', 70]], ['joe', ['savings', 70]], ['jane', ['savings', 70]])
淺拷貝:
person ──────→ [0] → 'name' (str, immutable)
[1] → ['savings', 100] ← hubby[1], wifey[1] (共享同一列表物件)
hubby ──────→ [0] → 'joe' (新字串)
[1] → 同一個列表
wifey ──────→ [0] → 'jane' (新字串)
[1] → 同一個列表
>> hubby_deep = copy.deepcopy(person)
>>> hubby_deep[1][1] = 50
>>> person, hubby_deep
(['name', ['savings', 100]], ['name', ['savings', 50]]) # 互不影響
| 場景 | 錯誤現象 | 正確做法 |
|---|---|---|
函數預設參數 def f(a=[]) | 所有呼叫共享同一列表 | def f(a=None): a = [] if a is None else a |
列表乘法 [[0]] * 3 | 三個元素指向同一內層列表 | [[0] for _ in range(3)] |
字典 .copy() 後修改嵌套 dict | 嵌套 dict 共享 | copy.deepcopy(d) |
類別屬性 items = [] | 所有實例共享列表 | def __init__(self): self.items = [] |
deepcopy 速度較慢 (遞迴 + 處理循環引用),大型資料結構慎用。json.loads(json.dumps(obj)) 可作為簡易深拷貝 (不支援 tuple、set、自訂類別)。def is_shared(obj1, obj2, path):
"""檢查 obj1 與 obj2 在 path 路徑下是否為同一物件"""
for p in path:
obj1 = obj1[p]
obj2 = obj2[p]
return obj1 is obj2
# 用法
is_shared(person, hubby, (1,)) # True (內層列表共享)
is_shared(person, hubby, (0,)) # False (字串不同)
理解淺/深拷貝機制,是寫出無副作用、可維護 Python 程式的關鍵。