萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 淺拷貝與深拷貝圖解與實戰陷阱

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、自訂類別)。
  • 不可變資料結構 (namedtuple, frozenset, dataclass frozen=True) 根本不需要拷貝。

判斷是否共享引用的技巧

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 程式的關鍵。

copyright © 萬盛學電腦網 all rights reserved