比较是 vs

一个常见的陷阱是混淆了相等比较运算符 is==

a == b 比较 ab 的值。

a is b 将比较 ab身份

为了显示:

a = 'Python is fun!'
b = 'Python is fun!'
a == b # returns True
a is b # returns False

a = [1, 2, 3, 4, 5]
b = a      # b references a
a == b     # True
a is b     # True
b = a[:]   # b now references a copy of a
a == b     # True
a is b     # False [!!]

基本上,is 可以被认为是 id(a) == id(b) 的简写。

除此之外,运行时环境的怪癖使事情进一步复杂化。由于 Python 机器试图为相同的对象使用更少的内存,因此与 is 相比,短字符串和小整数将返回 True

a = 'short'
b = 'short'
c = 5
d = 5
a is b # True
c is d # True

但是较长的字符串和较大的整数将分开存储。

a = 'not so short'
b = 'not so short'
c = 1000
d = 1000
a is b # False
c is d # False

你应该使用 is 来测试 None

if myvar is not None:
    # not None
    pass
if myvar is None:
    # None
    pass

is 的用途是测试哨兵(即一个独特的物体)。

sentinel = object()
def myfunc(var=sentinel):
    if var is sentinel:
        # value wasn’t provided
        pass
    else:
        # value was provided
        pass