我自己制作Fraction课程

时间:2018-03-17 18:02:20

标签: python fractions

我试图制作自己的Fraction课程&#39;。 几乎所有代码都可以正常工作,但在/><,这些代码无效。 我不知道我的代码有什么问题。

def gcd(m, n):
    while m%n != 0:
        m, n = n, m%n
    return n

class Fraction:
    '''Fractional class'''

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

    def __str__(self): 
        return str(self.num)+'/'+str(self.denom)

    def __add__(self, other): 
        new_num = self.num * other.denom + other.num * self.denom
        new_denom = self.denom * other.denom
        common = gcd(new_num, new_denom)
        return Fraction(new_num//common, new_denom//common)

    def __sub__(self, other): 
        new_num = self.num * other.denom - other.num * self.denom
        new_denom = self.denom * other.denom
        common = gcd(new_num, new_denom)
        return Fraction(new_num//common, new_denom//common)

    def __mul__(self, other): 
        new_num = self.num * other.num
        new_denom = self.denom * other.denom
        common = gcd(new_num, new_denom)
        return Fraction(new_num//common, new_denom//common)

    def __div__(self, other): 
        new_num = self.num * other.denom
        new_denom = self.denom * other.num
        common = gcd(new_num, new_denom)
        return Fraction(new_num//common, new_denom//common)


    def __equal__(self, other):
        return (self.num * other.denom) == (other.num * self.denom)

    def __big__(self, other):
        return str(self.num * other.denom) > str(other.num * self.denom)

    def __small__(self, other):
        return self.num * other.denom < other.num * self.denom



if __name__ == "__main__":

    f1 = Fraction(1,4)
    f2 = Fraction(1,2)
    print(f1+f2)
    print(f1 - f2)
    print(f1 * f2)
    print(f1 / f2) #not working

    print(f1 == f2) 
    print(f1 > f2) #not working
    print(f1 < f2) #not working

我得到以下输出:

3/4
-1/4
1/8
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-50cad0951bd1> in <module>()
     57     print(f1 - f2)
     58     print(f1 * f2)
---> 59     print(f1 / f2) #not working
     60 
     61     print(f1 == f2)

TypeError: unsupported operand type(s) for /: 'Fraction' and 'Fraction'

我是否正确定义了__div__

1 个答案:

答案 0 :(得分:2)

Python 3.x使用__truediv____floordiv____div__用于python 2.x。

要进行比较工作,您需要定义__lt____gt____ge____le__