python – 等于自建Fraction类的支持

class Fraction:
    """Class for performing fraction arithmetic.
    Each Fraction has two attributes: a numerator, n and a deconominator, d.
    Both must be integer and the deonominator cannot be zero."""

    def __init__(self,n,d):
        """Performs error checking and standardises to ensure denominator is 
positive"""
        if type(n)!=int or type(d)!=int:
            raise TypeError("n and d must be integers")
        if d==0:
            raise ValueError("d must be positive")
        elif d<0:
            self.n = -n
            self.d = -d
        else:
            self.n = n
            self.d = d

    def __str__(self):
        """Gives string representation of Fraction (so we can use print)"""
        return(str(self.n) + "/" + str(self.d))

    def __add__(self, otherFrac):
        """Produces new Fraction for the sum of two Fractions"""
        newN = self.n*otherFrac.d + self.d*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __sub__(self, otherFrac):
        """Produces new Fraction for the difference between two Fractions"""        
        newN = self.n*otherFrac.d - self.d*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __mul__(self, otherFrac):
        """Produces new Fraction for the product of two Fractions"""        
        newN = self.n*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __truediv__(self, otherFrac):
        """Produces new Fraction for the quotient of two Fractions"""        
        newN = self.n*otherFrac.d
        newD = self.d*otherFrac.n
        newFrac = Fraction(newN, newD)
        return(newFrac)

如上所示代码,我该怎么打印

Fraction(1,3) == Fraction(2,6)

例如:

Fraction(1,2) + Fraction(1,3)
Fraction(1,2) - Fraction(1,3)
Fraction(1,2) * Fraction(1,3)
Fraction(1,2) / Fraction(1,3)

它们都是每次计算的工作.当我尝试打印分数(1,3)==分数(2,6)时,它会显示为False.我如何让它计算为真?

如何在不使用导入分数的情况下执行此操作.

解决方法:

试试这个:

def __eq__(self, other):
    return  self.n*other.d == self.d*other.n

正如评论中指出的那样,没有必要实现__ne__.

编辑:根据本答案的评论中的要求,这是一种简化分数的方法.

分数的简化意味着将两个数除以最大公约数.正如here发布的那样,代码非常简单

# return the simplified version of a fraction
def simplified(self):
    # calculate the greatest common divisor
    a = self.n
    b = self.d
    while b:
        a, b = b, a%b
    # a is the gcd
    return Fraction(self.n/a, self.d/a)

我希望它有所帮助.

上一篇:在Java中添加后增量


下一篇:c# – “x as X!= null”和“x is X”总是返回相同的结果?