is判断是否为同一个对象,即判断是否引用了同一个内存地址。内存地址可以使用id(obj)获取。
==判断值是否相等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
import copy a = 1 b = 1 print(a == b) # True print(a is b) # True a = [] b = [] print(a == b) # True print(a is b) # False b = a print(a == b) # True print(a is b) # True b = copy.deepcopy(a) print(a == b) # True print(a is b) # False print("*" * 10) a = [1, 2, 3] b = [4, 5, 6] c = [a, b] # 列表c存储的是a和b的引用,而不是元素 print(c) # [[1, 2, 3], [4, 5, 6]] b.append(9) print(c) # [[1, 2, 3], [4, 5, 6, 9]] print("*" * 10) a = [1, 2, 3] b = [4, 5, 6] c = [a, b] # 列表c存储的也是a和b的引用 d = copy.deepcopy(c) print("c地址:{},d地址:{},c[0]-a地址:{},d[0]地址:{}".format(id(c), id(d), id(c[0]), id(d[0]))) # c地址:4341183944,d地址:4340997320,c[0]-a地址:4341094920,d[0]地址:4341095944 print(c[1] == d[1]) # True print(c[1] is d[1]) # False。deepcopy-深拷贝对内部引用的对象也进行了拷贝,即创建了新的a和b print(d) # [[1, 2, 3], [4, 5, 6]] a.append(7) print(d) # [[1, 2, 3], [4, 5, 6]] print(c) # [[1, 2, 3, 7], [4, 5, 6]] d[0].append(8) print(d) # [[1, 2, 3, 8], [4, 5, 6]] print(c) # [[1, 2, 3, 7], [4, 5, 6]] print("*" * 10) a = [1, 2, 3] b = [4, 5, 6] c = (a, b) # 元组c存储的也是a和b的引用 d = copy.deepcopy(c) print(d) # ([1, 2, 3], [4, 5, 6]) d[0].append(8) print(d) # ([1, 2, 3, 8], [4, 5, 6]) print(c) # ([1, 2, 3], [4, 5, 6]) b.append(9) print(d) # ([1, 2, 3, 8], [4, 5, 6]) print(c) # ([1, 2, 3], [4, 5, 6, 9]) print("*" * 10) a = [1, 2, 3] b = [4, 5, 6] c = [a, b] # [[1, 2, 3], [4, 5, 6]] d = copy.copy(c) print(c == d) # True print(c is d) # False print("c地址:{},d地址:{},c[0]-a地址:{},d[0]地址:{}".format(id(c), id(d), id(c[0]), id(d[0]))) # c地址:4359120136,d地址:4358933576,c[0]-a地址:4358933704,d[0]地址:4358933704 print(c[1] == d[1]) # True print(c[1] is d[1]) # True。copy-浅拷贝并未创建新的内部引用,仍使用原有的a和b a.append(7) print(c) # [[1, 2, 3, 7], [4, 5, 6]] print(d) # [[1, 2, 3, 7], [4, 5, 6]] print("*" * 10) a = [1, 2, 3] b = [4, 5, 6] c = (a, b) # ([1, 2, 3], [4, 5, 6]) d = copy.copy(c) print(c == d) # True print(c is d) # True print("c地址:{},d地址:{},c[0]-a地址:{},d[0]地址:{}".format(id(c), id(d), id(c[0]), id(d[0]))) # c地址:4360060296,d地址:4360060296,c[0]-a地址:4360117064,d[0]地址:4360117064 print(c[1] == d[1]) # True print(c[1] is d[1]) # True a.append(7) print(c) # [[1, 2, 3, 7], [4, 5, 6]] print(d) # [[1, 2, 3, 7], [4, 5, 6]] # ### 元组是不可变类型。copy.copy(tuple)浅拷贝的操作等同于等号=,直接引用原有的对象 ### |
声明
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/2657.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设