当前位置:   article > 正文

python哈希值与地址值_什么时候计算python对象的哈希值,为什么是-1的哈希值是不同的?...

python hash(-1)==hash(-2)

Following on from this question, I'm interested to know when is a python object's hash computed?

At an instance's __init__ time,

The first time __hash__() is called,

Every time __hash__() is called, or

Any other opportunity I might be missing?

May this vary depending on the type of the object?

Why does hash(-1) == -2 whilst other integers are equal to their hash?

解决方案

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).

The hash value -1 signalizes an error to 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.

See for yourself:

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/812118
推荐阅读
相关标签
  

闽ICP备14008679号