'is' 运算符不适用于具有相同标识的对象

The 'is' operator is not working on objects with the same identity

我是 运行:

Python 2.7.8 (default, Oct  6 2017, 09:25:50)
GCC 4.1.2 20070626 (Red Hat 4.1.2-14) on Linux 2

根据the documentation

The operators is and is not test for object identity: x is y is True if and only if x and y are the same object.

要获取对象的 身份 ,我们可以使用 id function.


如果我们打开一个新的 REPL 我们可以看到 300-6 具有相同的身份(在 CPython 上,这意味着两者都引用相同的内存地址) :

>>> id(300)
94766593705400
>>> id(-6)
94766593705400

请注意,实际值可能因执行而异,但它们始终相等。

但是,300 is -6 会产生 False:

>>> 300 is -6
False

我有几个问题:

执行完id(300)后,不再有对300的引用,所以id被释放。当您执行 id(6) 时,它会获得相同的内存块并存储 6。当您执行 -300 is 6 时,-3006 会同时被引用,因此它们将不再具有相同的地址。

如果您保留对 -3006 的引用,则会发生这种情况:

>>> a, b = -300, 6
>>> id(a)
some number
>>> id(b)
some different number; 6 is still in the other memory address.

注意:在 CPython 中,从 -5 到 256(我认为)的数字被缓存,并且将始终具有相同的地址,因此不会发生这种情况。

这是 id() 函数的记录行为:

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

示例代码中整数对象的生命周期只是函数调用(例如 id(300)),因为不存在对它的其他引用。