python如何评估"是"表达式?

Rah*_*hul 6 python

python中"is"表达式的不稳定行为.

>>> 258 -1 is 257
False
Run Code Online (Sandbox Code Playgroud)

>>> 258 -1 == 257
True
Run Code Online (Sandbox Code Playgroud)
  1. python如何评估"是"表达式?为什么它显示为假,尽管它是真的?

  2. 为什么它只发生在某些数字上?

    2 - 1是1真

工作得非常好.

Ash*_*ary 6

is用于身份检查,以检查两个变量是否指向同一个对象,同时==用于检查值.

来自文档:

运营商isis not测试对象标识:x is ytrue 当且仅当x和y是相同的对象.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) 
Run Code Online (Sandbox Code Playgroud)

但是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
Run Code Online (Sandbox Code Playgroud)


kin*_*all 2

is比较对象身份并True仅当双方是同一对象时才产生结果。出于性能原因,Python 维护小整数的“缓存”并重用它们,因此所有int(1)对象都是同一个对象。在 CPython 中,缓存的整数范围从 -5 到 255,但这是一个实现细节,因此您不应依赖它。如果要比较相等性,请使用==,而不是is