Let's say I have some Person objects, and I want to know if there are any in the list:
person in people?
I donβt care what the identifier of an object is, only that their properties are the same. So I put this in my base class:
# value comparison only def __eq__(self, other): return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) def __ne__(self, other): return not self.__eq__(other)
But in order to be able to check equality in sets, I also need to define a So hash ...
# sets use __hash__ for equality comparison def __hash__(self): return ( self.PersonID, self.FirstName, self.LastName, self.etc_etc... ).__hash__()
The problem is that I do not want to list each property, and I do not want to change the hash function every time I change properties.
So good to do it?
# sets use __hash__ for equality comparison def __hash__(self): values = tuple(self.__dict__.values()) return hash(values)
Is it normal, not excessive? In a situation with a web application.
Thanks.
python set hash
keeny
source share