识别对象,为什么 id(...) 的返回值会改变? [英] identifying objects, why does the returned value from id(...) change?

查看:59
本文介绍了识别对象,为什么 id(...) 的返回值会改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

id(对象)

这是一个整数(或长整数),它保证在此对象的生命周期内是唯一且恒定的.

你能解释一下这个输出吗?为什么j的id会改变?

<预><代码>>>>我=10>>>身份证(一)6337824>>>j=10>>>编号(j)6337824>>>j=j+1>>>编号(j)6337800>>>身份证(一)6337824

解决方案

因为整数是不可变的,所以每个整数值都是一个具有唯一 id 的不同对象.整数 1011 具有不同的 id.执行 j=j+1 不会更改现有整数对象的值,而是将 j 更改为指向 11 的对象.

看看当我们独立创建一个新变量 k 并将其赋值为 11 时会发生什么:

<预><代码>>>>j=10>>>编号(j)8402204>>>j=j+1>>>编号(j)8402192>>>k=11>>>编号(k)8402192

请注意,并非每个整数都有一个且只有一个对应的对象.这仅适用于 Python 决定缓存的小整数.大整数不会发生这种情况:

<预><代码>>>>x = 123456789>>>编号(x)8404568>>>y = 123456789>>>编号(y)8404604

参见 https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong:

<块引用>

当前的实现为 -5 到 256 之间的所有整数保留了一个整数对象数组,当您在该范围内创建一个 int 时,您实际上只是返回对现有对象的引用.

id(object)

This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.

Can you explain this output? Why does j's id change?

>>> i=10  
>>> id(i)  
6337824  
>>> j=10  
>>> id(j)  
6337824  
>>> j=j+1  
>>> id(j)  
6337800  
>>> id(i)  
6337824  

解决方案

Because integers are immutable, each integer value is a distinct object with a unique id. The integer 10 has a different id from 11. Doing j=j+1 doesn't change the value of an existing integer object, rather it changes j to point to the object for 11.

Check out what happens when we independently create a new variable k and assign it the value 11:

>>> j=10
>>> id(j)
8402204
>>> j=j+1
>>> id(j)
8402192
>>> k=11
>>> id(k)
8402192

Note that it is not always the case that every integer has one and only one corresponding object. This only happens for small integers that Python decides to cache. It does not happen for large integers:

>>> x = 123456789
>>> id(x)
8404568
>>> y = 123456789
>>> id(y)
8404604

See https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong:

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.

这篇关于识别对象,为什么 id(...) 的返回值会改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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