a = 1
,这个时候并不是把1
这个值赋给了a
,而是把1
这个对象的引用赋值给了a
。浅拷贝:浅拷贝会创建一个新的对象,但这个新对象的内容并不一定是原对象自身的复制(视具体数据而言)。具体来说,如果原对象的元素是可变的(比如列表或字典),浅拷贝会复制这些元素的引用,而不是元素本身。这意味着新对象和原对象会共享这些可变元素。如果对这些共享的元素进行修改,会影响到原对象。如果原对象的元素是不可变的(比如元组或字符串),浅拷贝则会复制这些元素的值,因为它们是不可变的,不会影响到原对象。浅拷贝通常有三种方式:自身构造器,切片和copy.copy()函数,不同数据类型(列表,元组,字典,集合 ,字符串)的浅拷贝会有差异,下面会逐一介绍。
深拷贝:重新分配一块新的内存,创建一个新的对象,并将原对象中的元素以递归的方式通过创建新的子对象拷贝到新的对象中。新的对象和原对象之间没有任何关系。深拷贝使用copy.deepcopy()函数实现
python自带数据类型: 列表,元组,字典,集合,字符串
>>> list1 = [1,2,3,4]
>>> list2 = list(list1)
>>> list2
[1, 2, 3, 4]
>>> id(list1)
140495553055488
>>> id(list2)
140495553080256
>>> list1==list2
True
>>> list1 = [1,2,3,4]
>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4]
>>> list1 is list2
False
>>> list1 == list2
True
>>> import copy
>>> list1 = [1,2,3,4]
>>> list2 = copy.copy(list1)
>>> list1
[1, 2, 3, 4]
>>> list2
[1, 2, 3, 4]
>>> list1 is list2
False
>>> list1 == list2
True
注:python中的可变序列有自己的copy()方法,即对于列表和字典这种的对象可以使用list.copy()或者dict.copy()跟copy.copy()函数是等价的。
>>> a = (1,2,3,4)
>>> b = tuple(a)
>>> a
(1, 2, 3, 4)
>>> b
(1, 2, 3, 4)
>>> a is b
True
>>> a == b
True
>>> a = (1,2,3,4)
>>> b = a[:]
>>> a is b
True
>>> a == b
True
>>> a
(1, 2, 3, 4)
>>> b
(1, 2, 3, 4)
>>> import copy
>>> a = (1,2,3,4)
>>> b = copy.copy(a)
>>> a
(1, 2, 3, 4)
>>> b
(1, 2, 3, 4)
>>> a is b
True
>>> a == b
True
>>> a = {1,2,3,4}
>>> b = set(a)
>>> a
{1, 2, 3, 4}
>>> b
{1, 2, 3, 4}
>>> a is b
False
>>> a == b
True
>>> import copy
>>> a = {1,2,3,4}
>>> b = copy.copy(a)
>>> a
{1, 2, 3, 4}
>>> b
{1, 2, 3, 4}
>>> a is b
False
>>> a ==b
True
>>> a = "1234"
>>> b = str(a)
>>> a
'1234'
>>> b
'1234'
>>> a is b
True
>>> a == b
True
>>> a = "1234"
>>> b = a[:]
>>> a
'1234'
>>> b
'1234'
>>> a is b
True
>>> a == b
True
>>> import copy
>>> a = "1234"
>>> b = copy.copy(a)
>>> a
'1234'
>>> b
'1234'
>>> a is b
True
>>> a ==b
True
>>> dict1 = {"a":1, 1:2}
>>> dict2 = dict(dict1)
>>> dict1
{'a': 1, 1: 2}
>>> dict2
{'a': 1, 1: 2}
>>> dict1 is dict2
False
>>> dict1 == dict2
True
>>> import copy
>>> dict1 = {"a":1, 1:2}
>>> dict2 = copy.copy(dict1)
>>> dict1
{'a': 1, 1: 2}
>>> dict2
{'a': 1, 1: 2}
>>> dict1 is dict2
False
>>> dict1 == dict2
True
>>> list1 = [[1, 2], (30, 40)]
>>> list2 = list(list1)
>>> list1.append(100)
>>> list1
[[1, 2], (30, 40), 100]
>>> list2
[[1, 2], (30, 40)]
>>> list1[0].append(3)
>>> list1
[[1, 2, 3], (30, 40), 100]
>>> list2
[[1, 2, 3], (30, 40)]
>>> list1[1] += (50,60)
>>> list1
[[1, 2, 3], (30, 40, 50, 60), 100]
>>> list2
[[1, 2, 3], (30, 40)]