下面我們就來聊一下:
運行效果:
==================================================
代碼部分:
==================================================
1 #python copy 2 ''' 3 個人認為: 4 淺拷貝:拷貝后,對象的引用沒有發生變化,而對象的行為發生變化,會反映到拷貝后的對象身上 5 深拷貝:拷貝后,對象的引用發生了變化,即對象不同,所以,即使對象再怎么變,也不會對其他對象產生影響 6 ''' 7 8 import copy 9 10 def shallow_copy(s): 11 '''make a shallow copy of s.''' 12 return copy.copy(s) 13 14 def deep_copy(d): 15 '''make a deep copy of d.''' 16 return copy.deepcopy(d) 17 18 def test_shallow(): 19 tem_data = ['a', 'c', 'e', 't', [1, 2, 3]] 20 print('被拷貝的源數據為:{}'.format(tem_data)) 21 s_copy = shallow_copy(tem_data) 22 print('進行淺拷貝....') 23 tem_data.append('Hongten') 24 tem_data[4].append('4') 25 print('修改源數據后:{}'.format(tem_data)) 26 print('拷貝后的數據為:{}'.format(s_copy)) 27 28 def test_deep(): 29 tem_data = ['a', 'c', 'e', 't', [1, 2, 3]] 30 print('被拷貝的源數據為:{}'.format(tem_data)) 31 s_copy = deep_copy(tem_data) 32 print('進行深拷貝....') 33 tem_data.append('Hongten') 34 tem_data[4].append('4') 35 print('修改源數據后:{}'.format(tem_data)) 36 print('拷貝后的數據為:{}'.format(s_copy)) 37 38 def test_s_copy(): 39 '''listB復制了listA,這時候listB是對listA的一個引用 40 他們指向的是同一個對象:[1, 2, 3, 4, 5],當我們試圖修 41 改listB[1] = 'Hongten'的時候,listB的所指向的對象的 42 行為發生了變化,即元素的值發生了變化,但是他們的引用是沒 43 有變化的,所以listA[1] = 'Hongten'也是情理之中的事''' 44 listA = [1, 2, 3, 4, 5] 45 listB = listA 46 listB[1] = 'Hongten' 47 print('listA = {}, listB = {}'.format(listA, listB)) 48 49 def test_clone(): 50 '''進行了列表的克隆操作,即拷貝了另一個列表,這樣的操作, 51 會創造出新的一個列表對象,使得listA和listB指向不同的對象, 52 就有着不同的引用,所以當listB[1] = 'Hongten'的時候, 53 listA[1]還是等於2,即不變''' 54 listA = [1, 2, 3, 4, 5] 55 listB = listA[:] 56 listB[1] = 'Hongten' 57 print('listA = {}, listB = {}'.format(listA, listB)) 58 59 def main(): 60 print('淺拷貝Demo') 61 test_shallow() 62 print('#' * 50) 63 print('深拷貝Demo') 64 test_deep() 65 print('#' * 50) 66 test_s_copy() 67 print('#' * 50) 68 test_clone() 69 70 if __name__ == '__main__': 71 main()