Not sure the best way to title this question, but how can I override or perform min(a, b)
or max(a, b)
on objects of a class i made? I can override the gt
and lt like below but I would like to override the min or max so that I'll be able to use something like max(a, b, c ,d)
. The class will have multiple property as well, but I think 2 for this example is sufficient.
class MyClass:
def __init__(self, item1, item2):
self.item1 = item1
self.item2 = item2
def __gt__(self, other):
if isinstance(other, MyClass):
if self.item1 > other.item1:
return True
elif self.item1 <= other.item1:
return False
elif self.item2 > other.item2:
return True
elif self.item2 <= other.item2:
return False
def __lt__(self, other):
if isinstance(other, MyClass):
if self.item1 < other.item1:
return True
elif self.item1 >= other.item1:
return False
elif self.item2 < other.item2:
return True
elif self.item2 >= other.item2:
return False
Ex:
a = MyClass(2,3)
b = MyClass(3,3)
print(a > b)
# False
I tried overriding __cmp__
but that doesnt seem to work.
Would like to be able to do max(a, b)
and return b
object