你的阅读不正确。该__eq__
方法用于相等性检查。文档只是说明__hash__
2 个对象的值也必须相同,并且a
( ie ) 为真。b
a == b
a.__eq__(b)
这是一个常见的逻辑错误:a == b
为真意味着它hash(a) == hash(b)
也为真。但是,蕴涵并不一定意味着等价,即除了先验之外,hash(a) == hash(b)
还意味着a == b
。
要使MyClass
compare 的所有实例彼此相等,您需要__eq__
为它们提供方法;否则 Python 将改为比较它们的身份。这可能会:
class MyClass(object):
def __hash__(self):
return 0
def __eq__(self, other):
# another object is equal to self, iff
# it is an instance of MyClass
return isinstance(other, MyClass)
现在:
>>> result = set()
>>> result.add(MyClass())
>>> result.add(MyClass())
1
实际上,您将基于__hash__
用于比较的对象的那些属性,__eq__
例如:
class Person
def __init__(self, name, ssn):
self.name = name
self.ssn = ssn
def __eq__(self, other):
return isinstance(other, Person) and self.ssn == other.ssn
def __hash__(self):
# use the hashcode of self.ssn since that is used
# for equality checks as well
return hash(self.ssn)
p = Person('Foo Bar', 123456789)
q = Person('Fake Name', 123456789)
print(len({p, q}) # 1