Suppose you have a simple class like A
below. The comparison methods are all virtually the same except for the comparison itself. Is there a shortcut around declaring the six methods in one method such that all comparisons are supported, something like B
?
I ask mainly because B
seems more Pythonic to me and I am surprised that my searching didn't find such a route.
class A:
def __init__(self, number: float, metadata: str):
self.number = number
self.metadata = metadata
def __lt__(self, other):
return self.number < other.number
def __le__(self, other):
return self.number <= other.number
def __gt__(self, other):
return self.number > other.number
def __ge__(self, other):
return self.number >= other.number
def __eq__(self, other):
return self.number == other.number
def __ne__(self, other):
return self.number != other.number
class B:
def __init__(self, number: float, metadata: str):
self.number = number
self.metadata = metadata
def __compare__(self, other, comparison):
return self.number.__compare__(other.number, comparison)