python - 未命名的 Python 对象具有相同的 id

标签 python python-2.7

让我们创建两个列表:

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

输出:

4366592912 4366591040

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

id(range(3))

输出:

4366623376

第二次:

id(range(3))

输出:

4366623376

我不确定如何解释这个。为什么这两个未命名列表的内存地址相同?

最佳答案

From the doc of id(object) :

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 值可能相同。

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

编辑:

查看 C 源代码向我们展示了 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是一个内存地址。

关于python - 未命名的 Python 对象具有相同的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24802740/

相关文章:

python - Python:URLError:<urlopen错误[Errno 10060]

python - 将 Pandas 列转换为 DateTime

python - 将 ctypes c_void_p 转换为 C 输出参数

python - Beautiful Soup 查找嵌套 div

python - Scrapy .css 选择具有特定属性名称和值的元素

Python 回溯损坏 : code out of sync with what is executed?

python - Windows 上这 4 种不同类型的 Python shebangs 有什么区别?

python - 将一个巨大的json字符串反序列化为python对象

Python:将一行展开为多行并进行计算

python - 从命令行运行脚本时防止图形关闭