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)

它们都是每次计算的工作。当我尝试打印 fraction(1,3) == fraction(2,6) 时,它显示为 False 。我怎样才能让它计算为 True

如果不使用 import fraction ,我该怎么做。

最佳答案

试试这个:

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)

我希望它有帮助。

关于python - 等于支持自建 Fraction 类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44003263/

10-12 18:20