问题描述
继this 问题,我想知道 python 对象的哈希值何时计算?
Following on from this question, I'm interested to know when is a python object's hash computed?
- 在实例的
__init__
时间, - 第一次调用
__hash__()
, - 每次调用
__hash__()
时,或 - 我可能会错过任何其他机会吗?
这可能会因对象的类型而异吗?
May this vary depending on the type of the object?
为什么 hash(-1) == -2
而其他整数等于它们的哈希?
Why does hash(-1) == -2
whilst other integers are equal to their hash?
推荐答案
散列通常在每次使用时计算,因为您可以很容易地检查自己(见下文).当然,任何特定对象都可以自由缓存其散列.例如,CPython 字符串会这样做,但元组不会(参见例如 这个被拒绝的错误报告)).
The hash is generally computed each time it's used, as you can quite easily check yourself (see below).Of course, any particular object is free to cache its hash. For example, CPython strings do this, but tuples don't (see e.g. this rejected bug report for reasons).
哈希值 -1 表示错误 在 CPython 中.这是因为C没有异常,所以需要使用返回值.当 Python 对象的 __hash__
返回 -1 时,CPython 实际上会默默地将其更改为 -2.
The hash value -1 signals an error in CPython. This is because C doesn't have exceptions, so it needs to use the return value. When a Python object's __hash__
returns -1, CPython will actually silently change it to -2.
亲眼看看:
class HashTest(object):
def __hash__(self):
print('Yes! __hash__ was called!')
return -1
hash_test = HashTest()
# All of these will print out 'Yes! __hash__ was called!':
print('__hash__ call #1')
hash_test.__hash__()
print('__hash__ call #2')
hash_test.__hash__()
print('hash call #1')
hash(hash_test)
print('hash call #2')
hash(hash_test)
print('Dict creation')
dct = {hash_test: 0}
print('Dict get')
dct[hash_test]
print('Dict set')
dct[hash_test] = 0
print('__hash__ return value:')
print(hash_test.__hash__()) # prints -1
print('Actual hash value:')
print(hash(hash_test)) # prints -2
这篇关于何时计算 python 对象的哈希值,为什么 -1 的哈希值不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!