注:set 对类对象去重,在于重写__eq__方法和__hash__方法,如果没有重写__hash__会导致People类对象不是可hash的
#!/usr/bin/env python # -*- coding: utf-8 -*- class People: def __init__(self, name, age, sex, weight): self.name = name self.age = age self.sex = sex self.weight = weight def __eq__(self,other): if self.name == other.name and self.sex == other.sex: return True return False def __hash__(self): return hash(self.name + self.sex) p1 = People('vector', 20, 'male', 50) p2 = People('vector', 30, 'male', 70) print(set([p1, p2]))