导入 copya = \'deepak\'b = 1, 2, 3, 4c = [1, 2, 3, 4]d = {1: 10, 2: 20, 3: 30}a1 = copy.copy(a)b1 = copy.copy(b)c1 = copy.copy(c)d1 = copy.copy(d) print(\'immutable - id(a)==id(a1)\', id(a...
import copy
a = "deepak"
b = 1, 2, 3, 4
c = [1, 2, 3, 4]
d = {1: 10, 2: 20, 3: 30}
a1 = copy.copy(a)
b1 = copy.copy(b)
c1 = copy.copy(c)
d1 = copy.copy(d)
print("immutable - id(a)==id(a1)", id(a) == id(a1))
print("immutable - id(b)==id(b1)", id(b) == id(b1))
print("mutable - id(c)==id(c1)", id(c) == id(c1))
print("mutable - id(d)==id(d1)", id(d) == id(d1))
我得到以下结果:
immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False
如果我执行深度复制:
a1 = copy.deepcopy(a)
b1 = copy.deepcopy(b)
c1 = copy.deepcopy(c)
d1 = copy.deepcopy(d)
结果是一样的:
immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False
如果我进行赋值操作:
a1 = a
b1 = b
c1 = c
d1 = d
结果是:
immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) True
mutable - id(d)==id(d1) True
有人能解释一下这些副本之间到底有什么区别吗?这和可变和不可变对象有关吗?如果是的话,你能给我解释一下吗?
对于不可变对象,创建副本没有多大意义,因为它们不会改变。对于可变对象, assignment
, copy
和 deepcopy
的行为不同。让我们通过示例分别讨论它们。
赋值操作只是将源的引用分配给目标,例如:
>>> i = [1,2,3]
>>> j=i
>>> hex(id(i)), hex(id(j))
>>> ('0x10296f908', '0x10296f908') #Both addresses are identical
现在 i
和 j
从技术上来说指的是同一个列表。 i
和 j
都具有相同的内存地址。对其中一个的任何更新都将反映在另一个中,例如:
>>> i.append(4)
>>> j
>>> [1,2,3,4] #Destination is updated
>>> j.append(5)
>>> i
>>> [1,2,3,4,5] #Source is updated
另一方面, copy
创建 deepcopy
变量的新副本。因此,对原始变量的更改现在不会反映在复制变量中,反之亦然。但是, copy
( 浅复制 )不会创建嵌套对象的副本,而是仅复制对嵌套对象的引用,而 deepcopy
( 深复制 )会递归复制所有嵌套对象。
和 copy
的行为 deepcopy
:
使用复制的平面列表示例:
>>> import copy
>>> i = [1,2,3]
>>> j = copy.copy(i)
>>> hex(id(i)), hex(id(j))
>>> ('0x102b9b7c8', '0x102971cc8') #Both addresses are different
>>> i.append(4)
>>> j
>>> [1,2,3] #Update of original list didn't affect the copied variable
使用复制的嵌套列表示例:
>>> import copy
>>> i = [1,2,3,[4,5]]
>>> j = copy.copy(i)
>>> hex(id(i)), hex(id(j))
>>> ('0x102b9b7c8', '0x102971cc8') #Both addresses are still different
>>> hex(id(i[3])), hex(id(j[3]))
>>> ('0x10296f908', '0x10296f908') #Nested lists have the same address
>>> i[3].append(6)
>>> j
>>> [1,2,3,[4,5,6]] #Update of original nested list updated the copy as well
使用 deepcopy 的平面列表示例:
>>> import copy
>>> i = [1,2,3]
>>> j = copy.deepcopy(i)
>>> hex(id(i)), hex(id(j))
>>> ('0x102b9b7c8', '0x102971cc8') #Both addresses are different
>>> i.append(4)
>>> j
>>> [1,2,3] #Update of original list didn't affect the copied variable
使用 deepcopy 的嵌套列表示例:
>>> import copy
>>> i = [1,2,3,[4,5]]
>>> j = copy.deepcopy(i)
>>> hex(id(i)), hex(id(j))
>>> ('0x102b9b7c8', '0x102971cc8') #Both addresses are still different
>>> hex(id(i[3])), hex(id(j[3]))
>>> ('0x10296f908', '0x102b9b7c8') #Nested lists have different addresses
>>> i[3].append(6)
>>> j
>>> [1,2,3,[4,5]] #Update of original nested list didn't affect the copied variable