Python 学习笔记(十三)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_35212491/article/details/81508305

列表保存了零个或多个其他对象的引用,类似C语言的指针数组。字典中保存的也是对象的引用。

赋值

赋值是两个变量都指向同一个对象,对象引用计数+1。

深拷贝和浅拷贝

字符串和数字创建后不可修改,每次修改后就是重新创建字符串或数字对象。python 对字符串和整数做了特殊优化。

In [1]: string1 = "abc"

In [2]: string2 = "abc"

In [3]: string1 is string2
Out[3]: True

In [4]: id(string1)
Out[4]: 4315793368

In [5]: id(string2)
Out[5]: 4315793368

In [6]: string2 = string2 + "D"

In [7]: id(string2)
Out[7]: 4347603408

浅拷贝

浅拷贝会拷贝生成一个新的对象,不会拷贝内部子对象。完全切片操作[:]list()tuple()copy.copy() 都属于浅拷贝。

In [1]: person = ['name', ['saving', 100.00]]

In [2]: hubby = person[:]

In [3]: wifey = list(person)

In [4]: [id(x) for x in [person, hubby, wifey]]
Out[4]: [4584675464, 4584407688, 4584675720]

In [5]: [[id(x) for x in z] for z in (person, hubby, wifey)]
Out[5]: [[4551931192, 4584675528], [4551931192, 4584675528], [4551931192, 4584675528]]

In [6]: person[1][1] = 50

In [7]: hubby[1][1]
Out[7]: 50

这里写图片描述

深拷贝

将内存中的数据也重新创建一份。 深拷贝需要用 copy.deepcopy 方法。

In [1]: import copy

In [2]: person = ['name', ['saving', 100.00]]

In [3]: tmp = copy.deepcopy(person)

这里写图片描述

猜你喜欢

转载自blog.csdn.net/sinat_35212491/article/details/81508305
今日推荐