当将新对象添加到python集中时,首先计算该对象的哈希码,然后,如果该集中已经存在一个或多个具有相同哈希码的对象,则将这些对象与新对象。
这样的结果是您需要在类上实现
__hash__(...)and
__eq__(...)方法。例如:
class Person: def __init__(self, name, age): self.name = name self.age = age def __eq__(self, other): return self.age == other.age def __hash__(self): return hash(self.age) def __repr__(self): return '<Person {}>'.format(self.name)tom = Person('tom', 18)mary = Person('mary', 22)mary2 = Person('mary2', 22)person_set = {tom, mary, mary2}print(person_set)# output: {<Person tom>, <Person mary>}但是,您应该非常仔细地考虑什么正确的实现
__hash__以及
__eq__应该为您的班级使用。上面的示例有效,但没有任何意义(例如,两者
__hash__和
__eq__仅根据年龄来定义)。



