为什么 id 函数对整数和浮点数的行为不同? [英] Why id function behaves differently with integer and float?

查看:30
本文介绍了为什么 id 函数对整数和浮点数的行为不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下代码,它给了我不同的输出.

<预><代码>>>>foo1 = 4>>>foo2 = 2+2>>>id(foo1)37740064L>>>id(foo2)37740064L>>>foo1 = 4.3>>>foo2 = 1.3+3.0>>>id(foo1)37801304L>>>id(foo2)37801232L>>>

我使用的是 python 2.7.2.为什么 id 函数在浮点数情况下返回不同的值,而在整数情况下返回相同的值?

解决方案

那是因为id在数值常量中的结果是实现定义的.

在您的情况下,Python 2.7.2,IIRC,问题是编译器构建了一些有用的整数常量作为单例(从 -1 到 100 左右).其基本原理是这些数字的使用频率如此之高,以至于每次需要时动态分配它们是没有意义的,它们只是被重复使用.

但是对于 float 值,常量单例优化没有用,除了 0.0 之外,它们太多了!因此,每次需要一个新的 float 值时,它都会被分配,并获得不同的 id.

要更深入地了解,请阅读源代码!这个文件来自Python3,但思路是相同:查找 small_ints 数组.

I tried the following code and It gave me different output.

>>> foo1 = 4
>>> foo2 = 2+2
>>> id(foo1)
37740064L
>>> id(foo2)
37740064L

>>> foo1 = 4.3
>>> foo2 = 1.3+3.0
>>> id(foo1)
37801304L
>>> id(foo2)
37801232L
>>>

I am using python 2.7.2. Why id function return different value in case of float but same value in case of integers?

解决方案

That is because the result of id in numeric constants is implementation defined.

In your case, Python 2.7.2, IIRC, the issue is that the compiler builds a few useful integer constants as singletons, (from -1 to 100 or so). The rationale is that these numbers are used so frequently that it makes no sense to dynamically allocate them each time they are needed, they are simply reused.

But that constant singleton optimization is not useful for float values, other than maybe 0.0, there are too many of them! So each time a new float value is needed it is allocated, and it gets a different id.

For a more deeply insight, read the source! This file is from Python3, but the idea is the same: look for the small_ints array.

这篇关于为什么 id 函数对整数和浮点数的行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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