作者:Shawn
python3.7
文档:
https://docs.python.org/3/library/copy.html
copy.copy(x)
copy.deepcopy(x)
import copy
a = [1,2,3,4,['a','b']]
b = a # 赋值
c = a[:] # 浅拷贝
d = copy.copy(a) # 浅拷贝
e = copy.deepcopy(a) # 深拷贝
a.append(5)
a[4].append('c')
print('a=',a)
print('b=',b)
print('c=',c)
print('d=',d)
print('e=',e)
============ RESTART: F:\PyWorkspace\Python100\100examples\007.py ============
a= [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b= [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c= [1, 2, 3, 4, ['a', 'b', 'c']]
d= [1, 2, 3, 4, ['a', 'b', 'c']]
e= [1, 2, 3, 4, ['a', 'b']]
class deepdark():
def __init__(self):
self.fantasy=list()
self.fantasy.append('oh')
def banana(self):
print(self.fantasy)
def boyNextDoor(self):
self.fantasy.append('my shoulder')
====================== RESTART: F:\PyWorkspace\blank.py ======================
>>> import copy
>>> a=deepdark()
>>> b=[1,a]
>>> c=copy.copy(b)
>>> d=copy.deepcopy(b)
>>> a.boyNextDoor()
>>> a.banana()
['oh', 'my shoulder']
>>> b[1].banana()
['oh', 'my shoulder']
>>> c[1].banana()
['oh', 'my shoulder']
>>> d[1].banana()
['oh']
>>> e=copy.copy(a)
>>> a.boyNextDoor()
>>> a.banana()
['oh', 'my shoulder', 'my shoulder']
>>> e.banana()
['oh', 'my shoulder', 'my shoulder']
>>> e.boyNextDoor()
>>> e.banana()
['oh', 'my shoulder', 'my shoulder', 'my shoulder']
>>> a.banana()
['oh', 'my shoulder', 'my shoulder', 'my shoulder']
>>> f=copy.deepcopy(a)
>>> a.boyNextDoor()
>>> a.banana()
['oh', 'my shoulder', 'my shoulder', 'my shoulder', 'my shoulder']
>>> f.banana()
['oh', 'my shoulder', 'my shoulder', 'my shoulder']