意外的 id 方法行为

Unexpected id method behaviour

简单来说,为什么这段代码returns假而不真:

a = 10
print(id(a) is id(a)) # why false?

id() returns 整数,并且相同的整数变量指向相同的整数对象。为什么它 returns false 呢?有什么区别:

a = 10
b = 10
print(a is b) # it returns True

感谢您的解释。

因为,虽然

a is a

id(a) 是一个大整数,不比较 is

>>> a = 10
>>> print(id(a) is id(a))
False
>>> print(id(a),id(a))
(44337068, 44337068)
>>>

检查 https://docs.python.org/2/c-api/int.html#c.PyInt_FromLong 哪些整数与 is 比较 - 但请记住这是一个实现细节所以不要依赖它(始终将整数与 == 进行比较):

>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False

(来自 "is" operator behaves unexpectedly with integers

为了进一步激励始终使用 ==,以下内容:

a = 300
b = 300
print(a is b)
print(a is 300)
def c(a): return a is 300
def d(a): return a is b
print(c(a))
print(d(a))

保存到文件并 运行 时,打印 TrueTrueFalseTrue...

如果您尝试这样做,例如

 print(str(id(id(a))) + " " + str(id(id(a))))
In [54]: print(str(id(id(a))) + " " + str(id(id(a))))
2460780951888 2460780951888

In [55]: print(str(id(id(a))) + " " + str(id(id(a))))
2460780951472 2460780951472

In [56]: print(str(id(id(a))) + " " + str(id(id(a))))
2460782062320 2460782062320

In [57]: print(str(id(id(a))) + " " + str(id(id(a))))
2460780951888 2460780951888

In [58]: print(str(id(id(a))) + " " + str(id(id(a))))
2460782473392 2460782475664

每次都会 return 一个大整数的新 ID

正如@thebjorn 所提到的,python 解释器不会缓存大整数,只有 -5 到 256 之间的整数(在 CPython 实现中)始终保持活动状态。

每次引用一个大整数时,都会为其创建一个新对象,而对于一个小整数,将继续使用同一个对象(作为优化),但是不能保证在所有情况下都如此 python 实施。