Python中“is”表达式的不稳定行为。
>>> 258 -1 is 257
False
并且
>>> 258 -1 == 257
True
Python如何评估“is”表达式?为什么它显示为false,即使它是true?
为什么只有一定范围的数字才会发生这种情况?
2 - 1 is 1 True
完全正常工作。
Python中“is”表达式的不稳定行为。
>>> 258 -1 is 257
False
>>> 258 -1 == 257
True
Python如何评估“is”表达式?为什么它显示为false,即使它是true?
为什么只有一定范围的数字才会发生这种情况?
2 - 1 is 1 True
完全正常工作。
is
用于身份检查,检查是否两个变量指向同一对象,而==
用于检查值。
is
和is not
这两个操作符用于测试对象的身份:x is y
当且仅当x和y是同一对象时为true
。x is not y
则产生相反的真值。
>>> id(1000-1) == id(999)
False
""" What is id?
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
"""
>>> 1000-1 is 999
False
>>> 1000-1 == 999
True
>>> x = [1]
>>> y = x #now y and x both point to the same object
>>> y is x
True
>>> id(y) == id(x)
True
>>> x = [1]
>>> y = [1]
>>> x == y
True
>>> x is y
False
>>> id(x),id(y) #different IDs
(161420364, 161420012)
但是Python会缓存一些小的整数(-5到256)和小字符串:为什么(0-6)等于-6 = False?
#small strings
>>> x = "foo"
>>> y = "foo"
>>> x is y
True
>>> x == y
True
#huge string
>>> x = "foo"*1000
>>> y = "foo"*1000
>>> x is y
False
>>> x==y
True
is
是用来比较对象身份的,只有当两个对象是同一个对象时才返回 True
。出于性能考虑,Python 维护了一个“缓存”小整数并重复使用它们,因此所有的 int(1)
对象都是同一个对象。在 CPython 中,缓存的整数范围为 -5 到 255,但这是一项实现细节,所以您不应该依赖它。如果您想要比较相等性,请使用 ==
而不是 is
。
foo = "foo"; foo is foo.strip()
也会返回 True
。 - mgilsonis
操作符用于检查对象的身份:通过调用258-1
创建的对象与通过257
创建的对象不是同一个对象。而==
操作符则检查所比较的对象的值是否相同。help('is')
。Python is
operator检查的是对象的身份(identity),而不是对象的值。两个整数必须在内部引用同一个实际对象,才能返回true。
由于Python维护了一个内部缓存,因此对于“小”整数,这将返回true,但是如果使用is
比较具有相同值的两个数字,则通常不会返回true。