未命名的 Python 对象具有相同的 id [英] Unnamed Python objects have the same id

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

问题描述

让我们创建两个列表:

x = range(3)
y = range(3)
print id(x), id(y)

出:

4366592912 4366591040

我创建了两个独立的列表,输出显示了两个不同的内存地址.这并不奇怪.但是现在让我们在没有赋值的情况下做同样的事情:

I created two independent lists, and the output shows two different memory addresses. This is not surprising. But now let's do the same thing without the assignment:

id(range(3))

出:

4366623376

第二次:

id(range(3))

出:

4366623376

我不知道如何解释这个.为什么这两个未命名列表具有相同的内存地址?

I am not sure how to interpret this. Why do these two unnamed lists have the same memory address?

推荐答案

摘自 的文档id(对象):

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

Return the "identity" of an object. This is an 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.

由于 id() 调用中的两个范围具有不重叠的生命周期,因此它们的 id 值可能相同.

Since the two ranges inside the id() calls have non-overlapping lifetimes, their id values may be the same.

分配给变量的两个范围具有重叠的生命周期,因此它们必须具有不同的 id 值.

The two ranges assigned to variables have overlapping lifetimes so they must have different id values.

查看 C 源代码向我们展示了builtin_id:

A look into the C sources shows us builtin_id:

builtin_id(PyObject *self, PyObject *v)
{
    return PyLong_FromVoidPtr(v);
}

对于PyLong_FromVoidPtr.>

PyLong_FromVoidPtr(void *p)
{
#if SIZEOF_VOID_P <= SIZEOF_LONG
    return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
#else

#ifndef HAVE_LONG_LONG
#   error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
#endif
#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
#   error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
#endif
    return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */

}

所以 ID 是一个内存地址.

So the ID is a memory address.

这篇关于未命名的 Python 对象具有相同的 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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