python3深拷贝和浅拷贝

1. 浅拷贝

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

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

python3深拷贝和浅拷贝_第1张图片

python3深拷贝和浅拷贝_第2张图片

2. 深拷贝

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

python3深拷贝和浅拷贝_第3张图片

进一步理解拷贝
python3深拷贝和浅拷贝_第4张图片

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)



面试可能会被面试官问到有关浅拷贝和深拷贝的问题

浅拷贝:如a = b,这种就是浅拷贝

深拷贝:copy.deepcopy()是深拷贝

             另外。copy.copy()根据拷贝对象是可变类型和不可变类型时,处理方式也不同,简单说copy会对原对象拷贝,但不会递归深拷贝

你可能感兴趣的:(Python)