1.在python中 a = b,a会指向b的引用。
In [1]: a = [1,2]
In [2]: b = a
In [3]: id(a)
Out[3]: 139921706771720
In [4]: id(b)
Out[4]: 139921706771720
2.在python中使用copy时,当数据是可变类型,会把需要的数据复制一份。例如
In [15]: import copy In [16]: a = [1,2] In [17]: b = copy.copy(a) In [18]: id(a) Out[18]: 139921706719176 In [19]: id(b) Out[19]: 139921664941320 In [20]: a.append(3) In [
由上面不难看出,当数据是不可变类型,copy会把数据复制一份,变成两份互不影响的数据,而当数据是不可变类型时,copy和赋值一样都是拿的引用。
但是,当列表中的元素存的是元素的引用时,copy会把列表复制一份,但是列表的元素是拿的是原列表元素的引用。例如:
In [27]: a = [1,2]
In [28]: b = [3,4]
In [29]: c = [a,b]
In [30]: d = copy.copy( c )
In [31]: id( c )
Out[31]: 139921676354312
In [32]: id(d)
Out[32]: 139921676322824
In [33]: id(c[0])
Out[33]: 139921664518216
In [34]: id(d[0])
Out[34]: 139921664518216
In [35]: a = [1,2]
In [36]: b =[3,4]
In [37]: c = [a,b]
In [38]: d = copy.deepcopy©
In [39]: id©
Out[39]: 139921706836744
In [40]: id(d)
Out[40]: 139921664502920
In [41]: id(c[0])
Out[41]: 139921664585032
In [42]: id(d[0])
Out[42]: 139921706859144
In [43]:
注意:浅拷贝当拷贝元素是不可变类型时,会进行再复制一份数据,当元素是不可变类型时,会拿到数据的引用。而深拷贝是递归的形式进行浅拷贝。
In [43]: a =[1,2]
In [44]: b =(3,4)
In [45]: c = (a,b)
In [46]: d = copy.copy©
In [47]: e = copy.deepcopy©
In [48]: id©
Out[48]: 139921707080648
In [49]: id(d)
Out[49]: 139921707080648
In [50]: id(e)
Out[50]: 139921706856328
In [51]: a.append(6)
In [52]: c
Out[52]: ([1, 2, 6], (3, 4))
In [53]: d
Out[53]: ([1, 2, 6], (3, 4))
In [54]: e
Out[54]: ([1, 2], (3, 4))
对于全部都是不可变类型,赋值,深拷贝,浅拷贝是一样的。都是拿到数据的引用:
In [1]: import copy In [2]: a =(1,2) In [3]: b=(1,2) In [4]: c =(a,b) In [5]: d = c In [6]: e = copy.copy(c) In [7]: f = copy.deepcopy(c) In [8]: id(c) Out[8]: 140700378949832 In [9]: id(d) Out[9]: 140700378949832 In [10]: id(e) Out[10]: 140700378949832 In [11]: id(f) Out[11]: 140700378949832