什么时候计算python对象的哈希值,为什么是-1的哈希值是不同的? [英] When is a python object's hash computed and why is the hash of -1 different?

查看:365
本文介绍了什么时候计算python对象的哈希值,为什么是-1的哈希值是不同的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继以这个问题,我很想知道什么时候是python对象的哈希计算
$ b


  1. 在一个实例的 __ init __ 时间内,
  2. 第一次调用 __ hash __()时,

  3. 每次 __ hash __()被调用,或者
  4. 我可能缺少其他任何机会?

这取决于对象的类型吗?



为什么 hash(-1)== -2 其他整数等于它们的散列值?

解决方案

通常在每次使用散列值时计算散列值,因为您可以很容易地检查自己(见下文)。
当然,任何特定对象都可以自由缓存它的散列。例如,CPython字符串执行此操作,但元组不会(例如,请参阅这个被拒绝的错误报告) 。



散列值 -1 向CPython发出错误。这是因为C没有例外,所以它需要使用返回值。当一个Python对象的 __ hash __ 返回-1时,CPython实际上会默默地将其改为-2。



  class HashTest(object):
def __hash __(self):
print('Yes! __hash__被调用!')
返回-1

hash_test = HashTest()

#所有这些都会打印出'Yes! __hash__被调用!':

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


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

  1. At an instance's __init__ time,
  2. The first time __hash__() is called,
  3. Every time __hash__() is called, or
  4. 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

这篇关于什么时候计算python对象的哈希值,为什么是-1的哈希值是不同的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆