gpt4 book ai didi

python - id() 函数是干什么用的?

转载 作者:IT老高 更新时间:2023-10-28 21:09:10 26 4
gpt4 key购买 nike

我读过 the Python 2 docs并注意到 id() 函数:

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

所以,我尝试使用带有列表的 id():

>>> list = [1,2,3]
>>> id(list[0])
31186196
>>> id(list[1])
31907092 // increased by 896
>>> id(list[2])
31907080 // decreased by 12

函数返回的整数是多少?它是 C 中内存地址的同义词吗?如果是,为什么整数不对应数据类型的大小?

id()什么时候用在实践中?

最佳答案

您的帖子提出了几个问题:

What is the number returned from the function?

它是“一个整数(或长整数),它保证在此对象的生命周期内是唯一且恒定的。(Python Standard Library - Built-in Functions)一个唯一的号码。不多也不少。将其视为 Python 对象的社会保险号或员工 ID 号。

Is it the same with memory addresses in C?

从概念上讲,是的,因为它们都保证在其一生中在其宇宙中是独一无二的。而在 Python 的一个特定实现中,它实际上是对应的 C 对象的内存地址。

If yes, why doesn't the number increase instantly by the size of the data type (I assume that it would be int)?

因为列表不是数组,而列表元素是引用,而不是对象。

When do we really use id( ) function?

几乎没有。您可以通过比较它们的 id 来测试两个引用是否相同,但是 is operator一直是推荐的方法。 id( ) 仅在调试情况下才真正有用。

关于python - id() 函数是干什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15667189/

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