Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Copy ใน Python: Shallow Copy vs Deep Copy

ใน Python การกำหนดตัวแปร b = a เป็นแค่ reference ชี้ไป object เดียวกัน ไม่ได้ copy ค่า

Reference Assignment

>> L1 = [1, 2, 3]
>>> L2 = L1
>>> id(L1), id(L2)
(2165544063496, 2165544063496)  # Same ID!

>>> L2[1] = 100
>>> L1, L2
([1, 100, 3], [1, 100, 3])  # ทั้งคู่เปลี่ยน!

Shallow Copy: copy.copy()

สร้าง object ใหม่ แต่ nested objects ยัง reference เดิม

>> import copy
>>> L1 = [[1, 2, 3], [4, 5, 6]]
>>> L2 = copy.copy(L1)

# Append to outer list - ไม่ส่งผลต่อ L1
>>> L2.append([10, 10, 10])
>>> L1, L2
([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6], [10, 10, 10]])

# Modify nested element - ส่งผลต่อ L1!
>>> L2[1][0] = 100
>>> L1, L2
([[1, 2, 3], [100, 5, 6]], [[1, 2, 3], [100, 5, 6]])

Deep Copy: copy.deepcopy()

สร้าง object ใหม่ และ recursive copy nested objects ทั้งหมด

>> L1 = [[1, 2, 3], [4, 5, 6]]
>>> L2 = copy.deepcopy(L1)

>>> L2[1][0] = 100
>>> L1, L2
([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [100, 5, 6]])
# L1 ไม่เปลี่ยน!

สรุปความแตกต่าง

AspectShallow CopyDeep Copy
Outer objectNewNew
Nested objectsShared referencesRecursively copied
Performanceเร็วกว่าช้ากว่า
Memoryน้อยกว่ามากกว่า
Use caseFlat structures, immutable nestedNested mutable structures

Built-in Shallow Copy Methods

# List
L2 = L1.copy()
L2 = L1[:]
L2 = list(L1)
L2 = copy.copy(L1)

# Dict
D2 = D1.copy()
D2 = dict(D1)
D2 = copy.copy(D1)

# Set
S2 = S1.copy()
S2 = set(S1)
S2 = copy.copy(S1)

เมื่อไหร่ใช้ Deep Copy?

  • Nested lists/dicts/objects ที่ mutable
  • ต้องการ isolate การเปลี่ยนแปลงอย่างสมบูรณ์
  • Implement __copy__ และ __deepcopy__ ใน custom classes ถ้าจำเป็น
class MyClass:
    def __init__(self, data):
        self.data = data
    
    def __copy__(self):
        return MyClass(self.data)  # shallow
    
    def __deepcopy__(self, memo):
        return MyClass(copy.deepcopy(self.data, memo))