深拷贝、浅拷贝

1. 浅拷贝

  • 浅拷贝是对于一个对象的顶层拷贝

通俗的理解是:拷贝了引用,并没有拷贝内容

2. 深拷贝

  • 深拷贝是对于一个对象所有层次的拷贝(递归)

进一步理解拷贝

In [23]: a = [11,22,33]

In [24]: b = [44,55,66]

In [25]: c = (a,b)

In [26]: e = copy.deepcopy(c)

In [27]: a.append(77)

In [28]: a
Out[28]: [11, 22, 33, 77]

In [29]: b
Out[29]: [44, 55, 66]

In [30]: c
Out[30]: ([11, 22, 33, 77], [44, 55, 66])

In [31]: e
Out[31]: ([11, 22, 33], [44, 55, 66])

In [32]: 

In [32]: 

In [32]: f = copy.copy(c)

In [33]: a.append(88)

In [34]: a
Out[34]: [11, 22, 33, 77, 88]

In [35]: b
Out[35]: [44, 55, 66]

In [36]: c
Out[36]: ([11, 22, 33, 77, 88], [44, 55, 66])

In [37]: e
Out[37]: ([11, 22, 33], [44, 55, 66])

In [38]: f
Out[38]: ([11, 22, 33, 77, 88], [44, 55, 66])

3. 拷贝的其他方式

浅拷贝对不可变类型和可变类型的copy不同
In [88]: a = [11,22,33]

In [89]: b = copy.copy(a)

In [90]: id(a)
Out[90]: 59275144

In [91]: id(b)
Out[91]: 59525600

In [92]: a.append(44)

In [93]: a
Out[93]: [11, 22, 33, 44]

In [94]: b
Out[94]: [11, 22, 33]

In [95]:

In [95]:

In [95]: a = (11,22,33)

In [96]: b = copy.copy(a)

In [97]: id(a)
Out[97]: 58890680

In [98]: id(b)
Out[98]: 58890680
  • 分片表达式可以赋值一个序列
    a = "abc"

    b = a[:]
  • 字典的copy方法可以拷贝一个字典
    d = dict(name="zhangsan", age=27)

    co = d.copy()
  • 有些内置函数可以生成拷贝(list)
    a = list(range(10))

    b = list(a)
  • copy模块中的copy函数
    import copy

    a = (1,2,3)

    b = copy.copy(a)