使列表子类可哈希化 [英] Making a list subclass hashable

查看:112
本文介绍了使列表子类可哈希化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从list派生一个类,为其添加一些实例属性,并使它可哈希化.有什么好方法(快速,整洁)?

I want to derive a class from list, add a few instance attributes to it, and make it hashable. What is a good (fast and neat) way to do it?

更新:

我删除了一个用例的冗长解释.我还将一个相关但独立的问题移至其他问题. /p>

I deleted a lengthy explanation of a use case. I also moved a related but separate issue into a different question.

推荐答案

这段代码很好.您正在复制列表,这可能会有点慢.

This code is fine. You're making a copy of the list, which could be a bit slow.

def __hash__(self):
    return hash(tuple(self.list_attribute))

如果想提高速度,可以有几种选择.

You have several options if you want to be faster.

  • list_attribute存储为元组,而不是列表(完全构建后)
  • init 时刻计算一次哈希并存储哈希值.您可以这样做是因为您的类是不可变的,因此哈希永远不会改变.
  • 编写您自己的哈希函数.这是元组的哈希函数,执行类似的操作.
  • Store list_attribute as a tuple, not a list (after it is fully constructed)
  • Compute the hash once at init time and store the hash value. You can do this because your class is immutable, so the hash will never change.
  • Write your own hash function. Here's the hash function for tuple, do something similar.

这篇关于使列表子类可哈希化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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