相关疑难解决方法(0)

如何在python中实现一个好的__hash__函数

实现具有多个属性的类时(如下面的玩具示例),处理散列的最佳方法是什么?

我猜测,__eq____hash__应该是一致的,但如何实现适当的哈希函数,能够处理所有属性?

class AClass:
  def __init__(self):
      self.a = None
      self.b = None

  def __eq__(self, other):
      return other and self.a == other.a and self.b == other.b

  def __ne__(self, other):
    return not self.__eq__(other)

  def __hash__(self):
      return hash((self.a, self.b))
Run Code Online (Sandbox Code Playgroud)

我读到这个问题,元组是可以清洗的,所以我想知道上面的例子是否合情合理.是吗?

python hash

93
推荐指数
3
解决办法
6万
查看次数

标签 统计

hash ×1

python ×1