id() 函数是做什么用的? [英] What is the id( ) function used for?

查看:58
本文介绍了id() 函数是做什么用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了 Python 2 文档 并注意到了 id() 函数:

<块引用>

返回对象的身份".这是一个整数(或长整数),保证在此对象的生命周期内是唯一且恒定的.生命周期不重叠的两个对象可能具有相同的 id() 值.

CPython 实现细节:这是对象在内存中的地址.

所以,我尝试使用 id() 和一个列表:

<预><代码>>>>列表 = [1,2,3]>>>id(列表[0])31186196>>>id(列表[1])31907092//增加了 896>>>id(列表[2])31907080//减少了 12

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

id() 什么时候使用?

解决方案

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

<块引用>

函数返回的数字是多少?

它是一个整数(或长整数),在其生命周期内保证此对象的唯一性和常量.";(Python 标准库 - 内置函数) 唯一编号.没有更多,也没有更少.将其视为 Python 对象的社会保险号或员工 ID 号.

<块引用>

和C中的内存地址一样吗?

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

<块引用>

如果是,为什么数字不会立即增加数据类型的大小(我假设它是 int)?

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

<块引用>

我们什么时候真正使用id()函数?

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

I read the Python 2 docs and noticed the id() function:

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.

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:

What is the number returned from the function?

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.

Is it the same with memory addresses in C?

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.

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

Because a list is not an array, and a list element is a reference, not an object.

When do we really use id( ) function?

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() 函数是做什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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