类Rational中的方法

时间:2013-12-06 19:07:29

标签: class oop python-3.x rational-number

我几乎完成了我的Class Rational,在实现比较时遇到了一些问题。 当我将Rational数字与int进行比较时,如果Rational是左操作数,那么一切都很好,但是当比较是int<理性,它不起作用..使用以下方法遇到此问题:__lt____gr____ge__ __le__。 我的一个方法:

def __lt__(self,other):
    n1=self.n
    d1=self.d
    if isinstance(other,Rational):
        n2=other.n
        d2=other.d
    elif isinstance(other,int):
        n2=other
        d2=1
    return (n1/d1)<(n2/d2)

1 个答案:

答案 0 :(得分:0)

例如:

>>> r2=Rational("0.25")
>>> r2
<Rational 1/4>
>>> r2<4
True
>>> 4<r2
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    4<r2
TypeError: unorderable types: int() < Rational()
>>>