0%

python | 值比较和引用比较

这里主要讲述了 python 中 ==is 的异同。


参考资料



解析


推荐你看我之前写的博文。

不可变对象

  • 基本类型
  • 字符串
  • 元组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
a = 1000
b = 1000
print(a is b) # True
print(a == b) # True

a = '哈哈'
b = '哈哈'
print(a is b) # True
print(a == b) # True

a = (1, 2, 3)
b = (1, 2, 3)
print(a is b) # True
print(a == b) # True

可变对象

  • 字典
  • 列表
  • 集合
  • 自定义对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
a = {'h': 1}
b = {'h': 1}
print(a is b) # False
print(a == b) # True

a = {1, 2, 3}
b = {1, 2, 3}
print(a is b) # False
print(a == b) # True


# 自定义对象
class Node:
def __init__(self, x):
self.val = x
self.next = None


n1 = Node(1)
n2 = Node(1)
print(a is b) # False
print(a == b) # True
请我喝杯咖啡吧~