浅拷贝、深拷贝和普通赋值操作有什么区别? [英] What is the difference between shallow copy, deepcopy and normal assignment operation?
问题描述
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
有人可以解释一下副本之间的区别吗?它是否与可变 & 相关?不可变对象?如果是这样,你能解释一下吗?
Can somebody explain what exactly makes a difference between the copies? Is it something related to mutable & immutable objects? If so, can you please explain it to me?
推荐答案
正常的赋值操作只会将新变量指向现有对象.docs 解释了浅拷贝和深拷贝的区别:
Normal assignment operations will simply point the new variable towards the existing object. The docs explain the difference between shallow and deep copies:
浅拷贝和深拷贝的区别只与复合对象(包含其他对象的对象,如列表或类实例):
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
浅拷贝构建了一个新的复合对象,然后(尽可能)将引用插入到其中,引用在原始对象中找到的对象.
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
深拷贝构造一个新的复合对象,然后递归地将在其中找到的对象的副本插入其中原创.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
这是一个小示范:
import copy
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
使用正常的赋值操作来复制:
Using normal assignment operatings to copy:
d = c
print id(c) == id(d) # True - d is the same object as c
print id(c[0]) == id(d[0]) # True - d[0] is the same object as c[0]
使用浅拷贝:
d = copy.copy(c)
print id(c) == id(d) # False - d is now a new object
print id(c[0]) == id(d[0]) # True - d[0] is the same object as c[0]
使用深拷贝:
d = copy.deepcopy(c)
print id(c) == id(d) # False - d is now a new object
print id(c[0]) == id(d[0]) # False - d[0] is now a new object
这篇关于浅拷贝、深拷贝和普通赋值操作有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!