你的读数不正确.__eq__
方法用于相等性判断.文件只是说明,对于a == b
(即a.__eq__(b)
)为真的两个对象a
和b
,__hash__
值也必须相同.
这是一个常见的逻辑错误:a == b
为真100 hash(a) == hash(b)
也为真.然而,暗示不一定意味着101,即除了先前的hash(a) == hash(b)
,还意味着a == b
.
要使MyClass
的所有实例彼此相等,需要为它们提供__eq__
方法;否则Python将比较它们的identities instead.这可能会:
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