How can I retain Uniqueness feature of Set for modifying attributes of user-defined instance after adding them into the Set?
like in the code below: both Person "Jack" and "John" are different in term of equality "Name" . So they both are added into the set but if I change Person "Jack" name to "John, then the 2 instance jack and john will be equal however my Set doesn't reflect that. They still consider those 2 instances are different
Note: this leads to potential bug when someone accidentally modifies the user-defined instances after they have been added into the set
Do we have a way to refresh the Set or how i can avoid this issue?
class Person:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return hash(self.name)
jack = Person("Jack")
john = Person("John")
set1 = {jack, john}
jack.name = "John"
print(set1) // return 2 instance instead of 1. This is undesired behavior because now both jack & john are equal