什么使用户定义类不可缓解? [英] What makes a user-defined class unhashable?

查看:134
本文介绍了什么使用户定义类不可缓解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档说,类是哈希表,只要它定义 __ hash __ 方法和 __ eq __ 方法。但是:

The docs say that a class is hashable as long as it defines __hash__ method and __eq__ method. However:

class X(list):
  # read-only interface of `tuple` and `list` should be the same, so reuse tuple.__hash__
  __hash__ = tuple.__hash__

x1 = X()
s = {x1} # TypeError: unhashable type: 'X'

使 X 不可取消?

请注意,我必须具有相同的列表(在正则相等性方面)被哈希到相同的值;否则,我将对散列函数违反此要求

Note that I must have identical lists (in terms of regular equality) to be hashed to the same value; otherwise, I will violate this requirement on hash functions:


唯一需要的属性是比较相等的对象具有
相同的哈希值

The only required property is that objects which compare equal have the same hash value

文档确实警告一个hashable对象在其生命周期中不应被修改,当然我不修改 X 创建后。

The docs do warn that a hashable object shouldn't be modified during its lifetime, and of course I don't modify instances of X after creation. Of course, the interpreter won't check that anyway.

推荐答案

只需设置 __ hash __ 方法的 tuple 类是不够的。你没有实际告诉它如何哈希任何不同。元组是哈希的,因为它们是不可变的。如果你真的想让你具体的例子工作,它可能是这样:

Simply setting the __hash__ method to that of the tuple class is not enough. You haven't actually told it how to hash any differently. tuples are hashable because they are immutable. If you really wanted to make you specific example work, it might be like this:

class X2(list):
    def __hash__(self):
        return hash(tuple(self))

case你实际上是定义如何哈希你的自定义列表子类。你只需要定义它如何生成一个哈希。您可以对任何您想要的哈希,而不是使用元组的哈希方法:

In this case you are actually defining how to hash your custom list subclass. You just have to define exactly how it can generate a hash. You can hash on whatever you want, as opposed to using the tuple's hashing method:

def __hash__(self):
    return hash("foobar"*len(self))

这篇关于什么使用户定义类不可缓解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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