【问题标题】:Methods in Class Rational类 Rational 中的方法
【发布时间】:2013-12-06 19:07:28
【问题描述】:

我几乎完成了我的 Class Rational,在实现比较时遇到了一点问题。 当我将 Rational 数与 int 进行比较时,如果 Rational 是左操作数,那么一切都很好,但是当比较是 int __lt__,@ 987654322@,__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)

【问题讨论】:

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


    【解决方案1】:

    例如:

    >>> 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()
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-19
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多