关于python面向对象中对对象有共同属性进行去重

class Person(object):
    def __init__(self, name, number):
        self.name = name
        self.number = number

我实例三个一样属性的对象

p1=Person("python",1)

p2=Person("python",1)

p3=Person("python",1)

然后正常情况print(set(p1,p2,p3))


很明显计算机显示的是三个不同的对象,那我要实现对象下指定相同属性进行去重该如何完成呢?

上代码:

class Person(object):
    def __init__(self, name, number):
        self.name = name
        self.number = number

    def __eq__(self, other):
        if isinstance(other, Person):
            return ((self.name == other.name) and (self.number == other.number))
        else:
            return False

    def __ne__(self, other):
        return (not self.__eq__(other))

    def __hash__(self):
        return hash(self.name) + hash(self.number)

然后再实例,print(set(p1,p2,p3)).运行




你可能感兴趣的:(python的思考)