id(float) 的值相同 [英] Same value for id(float)

查看:90
本文介绍了id(float) 的值相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,Python 中的一切都是对象,id() 应该(对吗?)为每个对象返回不同的数字.

就我而言,id(1) 返回 4298178968id(2) 返回 4298178944 但我获取所有浮点类型的相同值,id(1.1) 返回 4298189032id(2.2) 也返回 4298189032> 以及更多.

为什么我为所有浮点值获得相同的 id?

解决方案

Python 可以重用内存位置.

跑步时:

id(1.1)

你创建一个浮点值,请求它的 id(),然后 Python 再次删除这个值,因为没有任何引用它.然后当您创建另一个浮点值时,Python 可以重用相同的内存位置,因此 id(2.2) 很可能为 id()<返回相同的值/代码>:

<预><代码>>>>身份证(1.1)140550721129024>>>身份证(2.2)140550721129024

改为这样做:

float_one, float_two = 1.1, 2.2打印 id(float_one), id(float_two)

现在浮点值有对它们的引用(两个变量)并且不会被破坏,它们现在有不同的内存位置,因此 id() 值.

您看到小整数(从 -5 到 256)的不同 id() 值的原因是因为 这些值是实习的;Python 只创建 one 1 个整数对象并一遍又一遍地重用它.因此,这些整数都有一个唯一的内存地址,因为 Python 解释器本身已经引用了它们,并且在解释器退出之前不会删除它们.

As far as I know, everything is object in Python and the id() should (am I right?) return a different number for each object.

In my case, id(1) returns 4298178968, id(2) returns 4298178944 but I get the same values for all float types, id(1.1) returns 4298189032, id(2.2) also returns 4298189032 and more.

Why I get the same id for all float values?

解决方案

Python can reuse memory positions.

When you run:

id(1.1)

you create a float value, ask for its id(), and then Python deletes the value again because nothing refers to it. When you then create another float value, Python can reuse the same memory position and thus id(2.2) is likely to return the same value for id():

>>> id(1.1)
140550721129024
>>> id(2.2)
140550721129024

Do this instead:

float_one, float_two = 1.1, 2.2
print id(float_one), id(float_two)

Now the float values have references to them (the two variables) and won't be destroyed, and they now have different memory positions and thus id() values.

The reason you see different id() values for small integers (from -5 through to 256) is because these values are interned; Python only creates one 1 integer object and re-uses it over and over again. As a result, these integers all have a unique memory address regardles, as the Python interpreter itself already refers to them, and won't delete them until the interpreter exits.

这篇关于id(float) 的值相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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