Sep-29-2017, 12:34 PM
I've done some research and was able to implement the rich comparisons in my Person class. I have two questions,
1. Given the equals method how do I construct a good __hash__ function? I've read the documentation on the official website, but it was discussed on SO as having problems
1. Given the equals method how do I construct a good __hash__ function? I've read the documentation on the official website, but it was discussed on SO as having problems
def __init__(self, iden, firstname, lastname): self._firstname = firstname self._lastname = lastname self._iden = iden @property def identification_number(self): return self._iden @property def first_name(self): return self._firstname @property def last_name(self): return self._lastname def __eq__(self, other): return (self._iden, self._lastname.lower(), self._firstname.lower()) == (other.identification_number, other.last_name.lower(), other.first_name.lower())2. When creating the other rich comparisons, is it good practice to check if the operand is an instance of the class? For example, take the following __lt__ function:
def __lt__(self, other): if isinstance(other, Person): return (self._lastname.lower(), self._firstname.lower()) < (other.last_name.lower(), other.first_name.lower()) return NotImplementedIf it's considered bad practice, how then would I return NotImplemented error? The documentation clearly specifies that rich comparisons should return this error if the methods used for comparison haven't been implemented.