[Python] Limits the scope of object comparison to some of the attributes when adding to a set

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Person class like this:

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

    def __repr__(self):
    return '<Person {}>'.format(self.name)


    I want to add some instances of this class to a set, like this:

    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>}


    As you can see, there are 2 Marys in the set. How can I make it so that Person instances with the same age are considered the same person, and only added to the set once?

    In other words, how can I get a result of {<Person tom>, <Person mary>}?

    Continue reading...

Compartilhe esta Página