当前位置:   article > 正文

Python 中的hash_python hash方法

python hash方法

【问题背景】我自定义了Object类型,在用set()进行判重的时候发现重载了__eq__不起作用,总是认为不同的。

【问题原因】当自定义的Object作为set()集合元素时,由于set 属于哈希算法数据结构,因此判重时首先会判断hash,只有当hash相同时才会继续调用__eq__来判重。其他哈希数据结构也如此。

1 .魔法方法__hash__调用时机

请注意这个 __hash__魔法方法:

(1)被内置函数hash()调用

(2)hash类型的集合对自身成员的hash操作:set(), frozenset([iterable]), dict(**kwarg)

2 应用场景举例

2.1 仅用到__eq__判等,无需重载__hash__

当Object间使用判等符号来比对时仅会调用__eq__,这个时候不需要重载__hash__就能得到正确结果:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class Student(object):
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def __hash__(self):
        print 'Call __hash__'
        
    def __eq__(self, other):
        print 'Call __eq__'
        if not isinstance(other, Student):
            return False
        return self._name == other._name and self._age == other._age

if __name__ == '__main__':
    s1 = Student('aa', 20)
    s2 = Student('aa', 20)
    s3 = Student('bb', 21)
    print s1 == s2
    print s1 == s3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

2.2 哈希结构体的比对策略

在Python3.X系列版本中,如果仅自定义__eq__而没有定义__hash__,那么该Object无法作为哈希数据结构(set、frozenset、dict)元素。因为此时自动让__hash__返回None;

在Python2.X系列版本中,如果仅自定义__eq__而没有定义__hash__,那么仍然可以作为哈希数据结构(set、frozenset、dict)元素,此时会导致比对存在BUG,原因如下:

(1)哈希结构体首先调用__hash__比对Object,默认的哈希值生成是不一样的(与地址有关),因此总会判断两个Object不相等,哪怕内部赋值都一样也不行;

(2)哈希结构体在__hash__相等的情况下,会继续调用__eq__比对。

class Student(object):
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def __hash__(self):
        print 'Call __hash__'
        return hash(self._name + str(self._age))  # 请注意这里一定要返回hash值,否则None报错

    def __eq__(self, other):
        print 'Call __eq__'
        if not isinstance(other, Student):
            return False
        return self._name == other._name and self._age == other._age

if __name__ == '__main__':
    s1 = Student('aa', 20)
    s2 = Student('aa', 20)
    s3 = Student('bb', 21)
    test_set = set()
    test_set.add(s1)
    print s2 in test_set    # True
    print s3 in test_set    # False
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号