为什么(0-6)是-6 =假? [英] Why (0-6) is -6 = False?

查看:194
本文介绍了为什么(0-6)是-6 =假?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Python是操作符意外地以整数表现

今天我试图调试我的项目,几分钟的分析我得到了:

Today I tried to debug my project and after a few hours of analysing I'd got this:

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

但是,

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

你可以向我解释为什么吗?
也许这是某种错误或非常奇怪的行为。

Could you explain to me, why? Maybe this is some kind of bug or very strange behavior.

> 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共享相同的地址,因此测试通过。

All integers from -5 to 256 inclusive are cached as global objects sharing the same address with CPython, thus the is test passes.

这个工件在 http://www.laurentluce.com/posts/python-integer-objects-implementation/,我们可以在 http://hg.python.org/cpython中查看当前源代码/file/tip/Objects/longobject.c

This artifact is explained in detail in http://www.laurentluce.com/posts/python-integer-objects-implementation/, and we could check the current source code in http://hg.python.org/cpython/file/tip/Objects/longobject.c.


一个特定的结构用于引用小整数并共享它们访问速度快。它是一个262个整数对象指针的数组。这些整数对象在初始化期间被分配到我们上面看到的整数对象块中。小整数的范围是从-5到257.许多Python程序花费大量时间使用该范围内的整数,所以这是一个明智的决定。

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 257. Many Python programs spend a lot of time using integers in that range so this is a smart decision.

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

This is only an implementation detail of CPython and you shouldn't rely on this. For instance, PyPy implemented the id of integer to return itself, so (0-6) is -6 is always true even if they are "different objects" internally; it also allows you to configure whether to enable this integer caching, and even set the lower and upper bounds. But in general, objects retrieved from different origins will not be identical. If you want to compare equality, just use ==.

这篇关于为什么(0-6)是-6 =假?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆