__hash__方法,__eq__方法

class A(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __hash__(self):
        return hash(self.name)

    def __eq__(self, other):
        return self.name == other.name


if __name__ == '__main__':
    a1 = A("aa", 11)
    a2 = A("aa", 12)
    print("hash:", hash(a1) == hash(a2))     # __hash__方法会调用对象的__hash__方法
    print("==:", a1 == a2)  # '=='运算符会调用对象的__hash__方法和__eq__方法,两个方法都返回True,则运算结果为True
    print("is:", a1 is a2)  # 会比较两个对象的id(内存地址),检查两个对象是否是同一个对象

    a1set = {a1}
    a2set = {a2}
    print("set求差集:", a1set - a2set)    # set集合求差集是通过调用对象__hash__方法和__eq__方法(==运算)判断两个对象是否相同

运行结果:

hash: True
==: True
is: False
set求差集: set()

 

posted @ 2021-04-15 09:27  foreast  阅读(52)  评论(0编辑  收藏  举报