9

我有这样的Person课:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = 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>, <Person mary2>}

如您所见,集合中有 2 个玛丽。我怎样才能使Person具有相同年龄的实例被认为是同一个人,并且只添加到集合中一次?

换句话说,我怎样才能得到结果{<Person tom>, <Person mary>}

4

1 回答 1

37

当一个新对象被添加到 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>}

However, you should think very carefully about what the correct implementation of __hash__ and __eq__ should be for your class. The above example works, but is non-sensical (e.g. in that both __hash__ and __eq__ are defined only in terms of age).

于 2012-05-11T07:57:28.403 回答