Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,652 questions

51,529 answers

573 users

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, 2025 by avibootz

Related questions

3 answers 111 views
1 answer 63 views
3 answers 90 views
3 answers 117 views
1 answer 46 views
...