“is”运算符不处理具有相同标识的对象

2024-04-27 03:48:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我在跑步:

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.

要获得对象的标识,我们可以使用^{} function。你知道吗


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

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

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

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

>>> 300 is -6
False

我有几个问题:

  • 为什么300-6有相同的身份?你知道吗
  • 如果有,为什么300 is -6会产生False?你知道吗

Tags: andtheidfalsedefaultifobjectis
2条回答

执行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(我认为)的数字是缓存的,并且总是有相同的地址,所以这不会发生。你知道吗

这是^{}函数的记录行为:

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)),因为不存在对它的其他引用。你知道吗

相关问题 更多 >