id() 函数的 Python 文档说
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()?
请您参考如下方法:
hash 对于 equal 对象是相等的,甚至对于不相等的对象也可能是相等的。 hash 对于可变对象甚至不存在。
id 保证对象在其生命周期内是唯一的,它不关心变异。
用例完全不同。
>>> x, y, z = 1, 1.0, [1]
>>> hash(x), hash(y)
(1, 1)
>>> hash(z)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> id(x), id(y)
(10832608, 139668416746072)
>>> id(z)
139668282136008
>>> z.append(2)
>>> id(z)
139668282136008
>>> hash(-1), hash(-2)
(-2, -2)
