让我们创建两个列表:
x = range(3)
y = range(3)
print id(x), id(y)
输出:
4366592912 4366591040
我创建了两个独立的列表,输出显示了两个不同的内存地址。这并不奇怪。但是现在让我们在没有分配的情况下做同样的事情:
id(range(3))
输出:
4366623376
第二次:
id(range(3))
输出:
4366623376
我不确定如何解释这个。为什么这两个未命名列表的内存地址相同?
最佳答案
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(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/