class Food:
def __init__(self,taste,calorie):
self._taste = taste
self._calorie = calorie
def __gt__(self, other):
if self._taste == other._taste:
return(self._calorie < other._calorie)
else:
return self._taste > other._taste
strawberry = Food(9, 32)
potato = Food(6, 66)
print(strawberry < potato)
Hello, I'm a beginner studying Python. I'm asking you a question because I don't know something while studying.
In defining the class dunder method, we know that the __gt__(self, other)
method is when you invoke the self > other
operation.
However, if you look at the code above, the __gt_()
method is executed even though self<other
operation is performed when executing. I thought it would not be executed in __gt__()
because there was a separate method called self<other
called __gt_()
... Why is that in this case? I don't know even if I search it, so I'm leaving a question Help me.
To write down the answer, __lt__
can be invoked inside Python by __gt__
.
Therefore, __lt__, __gt_____
must be implemented to prevent side effects.
© 2024 OneMinuteCode. All rights reserved.