本文共 2246 字,大约阅读时间需要 7 分钟。
# Ruby[1] pry(main)> a = 1=> 1[2] pry(main)> b = a=> 1[3] pry(main)> a.object_id=> 3[4] pry(main)> b.object_id=> 3[5] pry(main)> a=2=> 2[6] pry(main)> b=> 1# 数组直接赋值给数组不属于拷贝, 只是内存地址的引用[7] pry(main)> array1 = ['a', 'b', 'c']=> ["a", "b", "c"][8] pry(main)> array2 = array1=> ["a", "b", "c"][9] pry(main)> array1 << 'd'=> ["a", "b", "c", "d"][10] pry(main)> array2=> ["a", "b", "c", "d"]# 浅拷贝[11] pry(main)> array1 = ['a', 'b', 'c']=> ["a", "b", "c"][12] pry(main)> array2 = array1.clone=> ["a", "b", "c"][13] pry(main)> array1 << 'd'=> ["a", "b", "c", "d"][14] pry(main)> array2=> ["a", "b", "c"]# 浅拷贝, 只会拷贝第一层, 第二层的内容不会拷贝[16] pry(main)> array1 = ['a', 'b', 'c', [1, 2, 3]]=> ["a", "b", "c", [1, 2, 3]][17] pry(main)> array2 = array1.clone=> ["a", "b", "c", [1, 2, 3]][18] pry(main)> array1[3] << 4=> [1, 2, 3, 4][19] pry(main)> array2=> ["a", "b", "c", [1, 2, 3, 4]]# 深拷贝,拷贝后的对象操作和原对象没有任何羁绊(关联)。[28] pry(main)> array1 = ['a', 'b', 'c', [1, 2, 3]]=> ["a", "b", "c", [1, 2, 3]][29] pry(main)> array2 = Marshal.load(Marshal.dump(array1))=> ["a", "b", "c", [1, 2, 3]][30] pry(main)> array1[3] << 4=> [1, 2, 3, 4][31] pry(main)> array1=> ["a", "b", "c", [1, 2, 3, 4]][32] pry(main)> array2=> ["a", "b", "c", [1, 2, 3]]
# Python3a = 1b = aprint(a, b)print(id(a), id(b))a = 2print(a, b)print(id(a), id(b))"""运行结果1 11445293568 14452935682 11445293568 1445293536"""# 列表直接赋值给列表不属于拷贝, 只是内存地址的引用list1 = ["a", "b", "c"]list2 = list1list1.append("d")print(list1, list2)print(id(list1), id(list2))"""运行结果['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']1947385383176 1947385383176"""# 浅拷贝list1 = ["a", "b", "c"]list2 = list1.copy()list1.append("d")print(list1, list2)print(id(list1), id(list2))""" 运行结果:['a', 'b', 'c', 'd'] ['a', 'b', 'c']1553315383560 1553315556936"""# 浅拷贝, 只会拷贝第一层, 第二层的内容不会拷贝list1 = ["a", "b", "c", [1, 2, 3]]list2 = list1.copy()list1[3].append(4)print(list1, list2)print(id(list1), id(list2))"""运行结果['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3, 4]]1386655149640 1386655185672"""# 深拷贝,拷贝后的对象操作和原对象没有任何羁绊(关联)。import copy list1 = ["a", "b", "c", [1, 2, 3]]list2 = copy.deepcopy(list1)list1[3].append(4)print(list1, list2)print(id(list1), id(list2))"""运行结果['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3]]1452762592904 1452762606664"""
转载地址:http://knjqi.baihongyu.com/