I wrote the following Author class in Python for a project I'm working on. I wanted to make sure that the rich comparisons and the methods I used to validate the constructor parameters were done properly.
Author class:
class Author:
def __init__(self, id, firstname, lastname):
self._validateid(id, "ID")
self._validate_author(firstname, "First Name")
self._validate_author(lastname, "Last Name")
self._id = id
self._firstname = firstname
self._lastname = lastname
def _validateid(self, id, error_message):
if id < 1:
raise ValueError(error_message + " is invalid")
def _validate_author(self, parameter, error_message):
if not parameter:
raise TypeError(error_message + " is missing")
@property
def iden(self):
return self._id
@property
def first_name(self):
return self._firstname
@property
def last_name(self):
return self._lastname
Rich Comparisons:
def __lt__(self, other):
if isinstance(other, Author):
return (self.iden, self.first_name.lower(), self.last_name.lower()) < (other.iden, other.first_name.lower(), other.last_name.lower())
return NotImplemented
def __le__(self, other):
if isinstance(other, Author):
return (self.iden, self.first_name.lower(), self.last_name.lower()) <= (other.iden, other.first_name.lower(), other.last_name.lower())
return NotImplemented
def __eq__(self, other):
if isinstance(other, Author):
return (self.iden, self.first_name.lower(), self.last_name.lower()) == (other.iden, other.first_name.lower(), other.last_name.lower())
return NotImplemented
def __ne__(self, other):
if isinstance(other, Author):
return (self.iden, self.first_name.lower(), self.last_name.lower()) != (other.iden, other.first_name.lower(), other.last_name.lower())
return NotImplemented
def __ge__(self, other):
if isinstance(other, Author):
return (self.iden, self.first_name.lower(), self.last_name.lower()) >= (other.iden, other.first_name.lower(), other.last_name.lower())
return NotImplemented
def __gt__(self, other):
if isinstance(other, Author):
return (self.iden, self.first_name.lower(), self.last_name.lower()) > (other.iden, other.first_name.lower(), other.last_name.lower())
return NotImplemented
def __hash__(self):
return hash((self.iden, self.first_name.lower(), self.last_name.lower()))
__hash__
could just return the id... \$\endgroup\$(lastname, firstname, id)
, instead of(id, lastname, firstname)
, which will always sort byid
first. \$\endgroup\$