Python对象拷贝

直接‘show me the code’,懒得长篇大论一堆文字

1:赋值

>>> a = [1, [1]]
>>> b = a
>>> a[1][0] = 2
>>> print a, b
[1, [2]] [1, [2]]
>>> a[0] = 2
>>> print a, b
[2, [2]] [2, [2]]
>>> a.append(3)
>>> print a, b
[2, [2], 3] [2, [2], 3]
>>> a[1].append(4)
>>> print a, b
[2, [2, 4], 3] [2, [2, 4], 3]

赋值其实是对象的引用,而python通过传递引用处理对象,列表对象的引用分别赋值给a和b,也就是a和b都引用这相同的一个对象,所以无论怎么修改对象的内容,a和b结果都一样是修改后的内容,并没有一个原始,没有被修改的copy

2:切片,copy,list

>>> a = [1, [1]]
>>> b = a[:]
>>> a[1][0] = 2
>>> print a, b
[1, [2]] [1, [2]]
>>> a[0] = 2
>>> print a, b
[2, [2]] [1, [2]]
>>>
>>> import copy
>>> a = [1, [1]]
>>> b = copy.copy(a)
>>> a[1][0] = 2
>>> print a, b
[1, [2]] [1, [2]]
>>> a[0] = 2
>>> print a, b
[2, [2]] [1, [2]]
>>>
>>> a = [1, [1]]
>>> b = list(a)
>>> a[1][0] = 2
>>> print a, b
[1, [2]] [1, [2]]
>>> a[0] = 2
>>> print a, b
[2, [2]] [1, [2]]

这三种方法都是浅拷贝,虽然生成了一个新对象,但是对象内部的属性和内容依然引用了原对象,所以在给列表第二个元素列表元素重新赋值2的时候,a和b都改变了;但是通过a来进行第一个元素重新赋值2的时候,b却没有变,原因是整型是不可变类型,也就是说在进行a[0] = 2的时候,会重新创建一个整型对象2,而b缺没变

3:deepcopy

>>> import copy
>>> a = [1, [1]]
>>> b = copy.deepcopy(a)
>>> a[1][0] = 2
>>> print a, b
[1, [2]] [1, [1]]
>>> a[0] = 2
>>> print a, b
[2, [2]] [1, [1]]

这种方法就是从原来对象重新复制一个全新的对象,内部属性和内容也全部递归地修改了

发表回复