python 对象有三个基本要素,分别是:id
, type
, value
is
是对id进行比较, 而 ==
是对值进行比较
example1:
x = [1, 2, 3]
y = x
z = [1, 2, 3]
print(x == y)
print(x is y)
print(x == z)
print(x is z)
print(id(x)) # x id
print(id(y)) # y id
print(id(z)) # z id
result:
True
True
True
False
140012008531336
140012008531336
140012008532936
可以看出x, y的id相同,而z的id与x,y不同。
example2:
x = 1
y = 1
print(x is y)
a = 'as'
b = 'as'
print(a is b)
a = (1, 2, 3)
b = (1, 2, 3)
print(a is b)
True
True
False
可以看出,在字符串和数值值的情况下,为true,这部分我觉得应该是python内部的机制,如果指向一个常量,那么直接将指针指到这个常量。所以id相同。