问题描述
我阅读了 Python 2 文档 并注意到了 id()
函数:
返回对象的身份".这是一个整数(或长整数),保证在此对象的生命周期内是唯一且恒定的.生命周期不重叠的两个对象可能具有相同的 id() 值.
CPython 实现细节:这是对象在内存中的地址.
所以,我尝试使用 id()
和一个列表:
函数返回的整数是多少?它是 C 中内存地址的同义词吗?如果是这样,为什么整数不对应数据类型的大小?
id()
什么时候使用?
您的帖子提出了几个问题:
函数返回的数字是多少?
它是一个整数(或长整数),在其生命周期内保证此对象的唯一性和常量.";(Python 标准库 - 内置函数) 唯一编号.没有更多,也没有更少.将其视为 Python 对象的社会保险号或员工 ID 号.
和C中的内存地址一样吗?
从概念上讲,是的,因为他们都保证在他们的一生中在他们的宇宙中都是独一无二的.而在 Python 的一种特定实现中,它实际上是对应的 C 对象的内存地址.
如果是,为什么数字不会立即增加数据类型的大小(我假设它是 int)?
因为列表不是数组,列表元素是引用,而不是对象.
我们什么时候真正使用id()
函数?
几乎没有.您可以通过比较它们的 id 来测试两个引用是否相同,但是 is
运算符 一直是推荐的方法.id( )
仅在调试情况下才真正有用.
I read the Python 2 docs and noticed the id()
function:
So, I experimented by using id()
with a list:
>>> list = [1,2,3]
>>> id(list[0])
31186196
>>> id(list[1])
31907092 // increased by 896
>>> id(list[2])
31907080 // decreased by 12
What is the integer returned from the function? Is it synonymous to memory addresses in C? If so, why doesn't the integer correspond to the size of the data type?
When is id()
used in practice?
Your post asks several questions:
It is "an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime." (Python Standard Library - Built-in Functions) A unique number. Nothing more, and nothing less. Think of it as a social-security number or employee id number for Python objects.
Conceptually, yes, in that they are both guaranteed to be unique in their universe during their lifetime. And in one particular implementation of Python, it actually is the memory address of the corresponding C object.
Because a list is not an array, and a list element is a reference, not an object.
Hardly ever. You can test if two references are the same by comparing their ids, but the is
operator has always been the recommended way of doing that. id( )
is only really useful in debugging situations.
这篇关于id() 函数是做什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!