How to create a set of objects in Python

1 Answer

0 votes
# Step 1: Define a class
class Person:
    def __init__(self, name, age):
        """
        The constructor method initializes a person object with a name and an age.
        """
        self.name = name
        self.age = age

    def __repr__(self):
        """
        Provides a string representation of the Person object.
        Useful for displaying the object in a readable format.
        """
        return f"Person(name={self.name}, age={self.age})"

    def __eq__(self, other):
        """
        Defines equality between two Person objects.
        Two objects are considered equal if they have the same name and age.
        """
        return self.name == other.name and self.age == other.age

    def __hash__(self):
        """
        Generates a unique hash value based on the name and age.
        This allows Person objects to be used in hash-based collections like sets.
        """
        return hash((self.name, self.age))

# Step 2: Create instances of the class
person1 = Person("Robert", 45)    # Creating an instance with name "Robert" and age 45
person2 = Person("Jennifer", 38)  # Creating an instance with name "Jennifer" and age 38
person3 = Person("Robert", 45)    # Duplicate of person1 (same name and age)
person4 = Person("Sharon", 51)    # Another unique person instance

# Step 3: Add objects to a set
# Since sets don't allow duplicate values, person3 won't be included
people_set = {person1, person2, person3, person4}

# Print the set to observe the unique entries
print(people_set)



'''
run:

{Person(name=Robert, age=45), Person(name=Jennifer, age=38), Person(name=Sharon, age=51)}

'''

 



answered Apr 22 by avibootz

Related questions

...