## 浅拷贝、深拷贝和正常作业到底有什么区别？

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