(2018-04-07.Python从Zero到One)一、python高级编程__1.2.5深拷贝、浅拷贝

上一篇文章为:→1.2.4==、is

深拷贝、浅拷贝

1. 浅拷贝

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

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

(2018-04-07.Python从Zero到One)一、python高级编程__1.2.5深拷贝、浅拷贝_第1张图片
day12_其他知识-01.png
(2018-04-07.Python从Zero到One)一、python高级编程__1.2.5深拷贝、浅拷贝_第2张图片
day12_其他知识-02.png

2. 深拷贝

  • 深拷贝是对于一个对象所有层次的拷贝(递归)
(2018-04-07.Python从Zero到One)一、python高级编程__1.2.5深拷贝、浅拷贝_第3张图片
day12_其他知识-03.png
进一步理解拷贝
(2018-04-07.Python从Zero到One)一、python高级编程__1.2.5深拷贝、浅拷贝_第4张图片
day12_其他知识-04.png
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)

下一篇文章为:→1.2.6进制、位运算

你可能感兴趣的:((2018-04-07.Python从Zero到One)一、python高级编程__1.2.5深拷贝、浅拷贝)