浅拷贝，深层拷贝和正常赋值操作的区别究竟是什么？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (23)
``````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
``````

2 个回答

• 浅拷贝构造一个新的复合对象，然后（尽可能）将引用插入到原始对象中。
• 深层副本构造一个新的复合对象，然后递归地将副本插入到原始对象中找到的对象。

``````import copy

a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
``````

``````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
``````