Is it possible to implement a method of a class so that objects of it works with set() function? So Set(objarray) would return unique objects. Of course, creating my own set is an option, but I just don’t want to reinvent the wheel if it is already there.
EDIT : I think I got your guys confused with my English. This is what I have in my class – I have a Person class that has person name and address as its members. This is what I want to do –
persons = []
for i in range (50):
name = raw_input("Enter Name")
address = raw_input("Address")
persons.append(Person(name,address))
unique = Set(persons) #would only return one person from an address.
#The rest from the same address will be removed
I hope that clear confusion.
Yes. First, if your class implements neither
__hash__nor__eq__, then they are already hashable (theidis used as the hash value and comparisons are done byis).Or, if you implement
__hash__and__eq__, then your class instances can be safely used in a set or as dictionary keys:If you want to be able to call
setdirectly on instances of your class, overload__iter__so that the class instances appear to be iterable: