gpt4 book ai didi

python - 为什么(0-6)是-6 = False?

转载 作者:IT老高 更新时间:2023-10-28 12:32:12 24 4
gpt4 key购买 nike

Possible Duplicate:
Python “is” operator behaves unexpectedly with integers

今天我尝试调试我的项目,经过几个小时的分析,我得到了这个:

>>> (0-6) is -6
False

但是,

>>> (0-5) is -5
True

你能解释一下,为什么?也许这是某种错误或非常奇怪的行为。

> Python 2.7.3 (default, Apr 24 2012, 00:00:54) [GCC 4.7.0 20120414 (prerelease)] on linux2
>>> type(0-6)
<type 'int'>
>>> type(-6)
<type 'int'>
>>> type((0-6) is -6)
<type 'bool'>
>>>

最佳答案

从 -5 到 256 的所有整数都被缓存为与 CPython 共享相同地址的全局对象,因此 is 测试通过。

此神器在http://www.laurentluce.com/posts/python-integer-objects-implementation/ 中有详细说明,我们可以查看http://hg.python.org/cpython/file/tip/Objects/longobject.c中的当前源代码.

A specific structure is used to refer small integers and share them so access is fast. It is an array of 262 pointers to integer objects. Those integer objects are allocated during initialization in a block of integer objects we saw above. The small integers range is from -5 to 256. Many Python programs spend a lot of time using integers in that range so this is a smart decision.

这只是 CPython 的一个实现细节,你不应该依赖它。 例如,PyPy实现了整数的 id 返回自身,因此 (0-6) is -6 始终为真,即使它们在内部是“不同的对象”;它还允许您配置是否启用此整数缓存,甚至设置下限和上限。但一般来说,从不同来源检索到的对象不会是相同的。如果要比较相等性,只需使用 ==

关于python - 为什么(0-6)是-6 = False?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11476190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com