python 浅拷贝和深拷贝

时间:2022-06-28 21:39:00

1.所谓浅拷贝只是对引用的拷贝(只拷贝父对象)


2.所谓深拷贝就是对对象的资源进行拷贝


user1@ubuntu:~$ python
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1,2,3,'a','b','c']
>>>
>>> b = a
>>> b
[1, 2, 3, 'a', 'b', 'c']
>>> id(a)
29240136
>>> id(b)
29240136
>>> a.append('d')
>>> id(a)
29240136
>>> b
[1, 2, 3, 'a', 'b', 'c', 'd']
>>> a
[1, 2, 3, 'a', 'b', 'c', 'd']
>>> b.append(4)
>>> b
[1, 2, 3, 'a', 'b', 'c', 'd', 4]
>>> a
[1, 2, 3, 'a', 'b', 'c', 'd', 4]
>>> import copy
>>> a = [1,2,3,['a','b','c']]
>>> a
[1, 2, 3, ['a', 'b', 'c']]
>>> b=a
>>> b
[1, 2, 3, ['a', 'b', 'c']]
>>> c = copy.copy(a) #浅拷贝
>>> c
[1, 2, 3, ['a', 'b', 'c']]
>>> id(a)
29430128
>>> id(b)
29430128
>>> id(c)
29463904
>>>
>>> a.append('d')
>>> a
[1, 2, 3, ['a', 'b', 'c'], 'd']
>>> b
[1, 2, 3, ['a', 'b', 'c'], 'd']
>>> c
[1, 2, 3, ['a', 'b', 'c']]
>>>
>>> id(a[0])
28477368
>>> id(c[0])
28477368
>>>
>>> id(a[3])
29429840
>>> id(c[3])
29429840
>>> a[3].append('d')
>>> a
[1, 2, 3, ['a', 'b', 'c', 'd'], 'd']
>>> c
[1, 2, 3, ['a', 'b', 'c', 'd']]
>>>
>>>
>>>
>>>
>>>
>>> a
[1, 2, 3, ['a', 'b', 'c', 'd'], 'd']
>>> d = copy.deepcopy(a) #深拷贝
>>> d
[1, 2, 3, ['a', 'b', 'c', 'd'], 'd']
>>> id(a)
29430128
>>> id(d)
33663168
>>> id(a[0])
28477368
>>> id(d[0])
28477368
>>> id(a[3])
29429840
>>> id(d[3])
33664320
>>> a
[1, 2, 3, ['a', 'b', 'c', 'd'], 'd']
>>> d
[1, 2, 3, ['a', 'b', 'c', 'd'], 'd']
>>> a.append('d')
>>> a
[1, 2, 3, ['a', 'b', 'c', 'd'], 'd', 'd']
>>> d
[1, 2, 3, ['a', 'b', 'c', 'd'], 'd']
>>>
>>> a[3].append('x')
>>> a
[1, 2, 3, ['a', 'b', 'c', 'd', 'x'], 'd', 'd']
>>> d
[1, 2, 3, ['a', 'b', 'c', 'd'], 'd']
>>>