Python comparative computation problem

Asked 1 years ago, Updated 1 years ago, 78 views

class Fraction:

    def __init__(self, num, denom):
        self._num = num
        self._denom = denom

    def __repr__(self):
        return str(self)

    def __str__(self):
        return str(self._num) + "/" + str(self._denom)

    def __gt__(self, other):
        return (self._num * other._denom) < (other._num * self._denom)

if __name__ == "__main__":

    f1 = Fraction(1, 4)
    f2 = Fraction(1, 5)

    print(f"{f1} < {f2} ->> {f1 < f2}") 

It's a Python question. I've made the code like above. It's a task that defines a function that compares the size of a fraction.

If you turn it around

1/4 < 1/5 ->> True

It comes out like this. Shouldn't it be 1/4 < 1/5 -> > False? I'm asking you a question because I think the code runs well but it seems strange. What's the problem?

python compare

2022-09-21 11:44

1 Answers

I thought it was strange, so I looked at the official document .

Specifically, (…)) gt(a, b) is equivalent to a > b, and (…)

To write what you want, you need to define __lt__(self, other).


2022-09-21 11:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.