支持自建分数类的等式操作

4
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。 如何让它计算为True

不使用import fraction,我该怎么做呢?


3
你需要实现 __eq__ 方法。这个方法用于决定两个对象是否相等。 - khelwood
3个回答

4

试试这个:

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

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

编辑:根据对这个答案的评论的要求,这里有一个简化分数的方法。

简化分数意味着将两个数字都除以最大公约数。如在此处发布的那样,代码相当简单。

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

我希望可以帮到您。

@ko-ko 顺便提一下,你报告的是 ("d must be positive"),但实际上你想表达的是 ("d must be non-zero") - Pablo Gutierrez Marques
谢谢@MSeifert!我之前不知道这个。 - Pablo Gutierrez Marques
1
难道不应该是 return self.n*other.d == self.d*other.n 吗? - Mark Beilfuss
非常聪明的解决方法!+1。个人而言,我会在__init__期间“简化”分数,因为这样对于所有操作来说更方便,但你的方法绝对可行。 - MSeifert
我喜欢这种简单的方式,当事情很简单时就不需要把它变得复杂。 - Ludisposed
显示剩余3条评论

2

数据模型指定__eq__作为实现==检查的方法。

一个非常简单的__eq__实现方式如下:

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

这将适用于Fraction(1, 2) == Fraction(1, 2),但不适用于Fraction(1, 2) == Fraction(2, 4)

您需要修改__eq__方法的内容,以便允许比较倍数。


1
在Python中,如果你想要自定义“==”操作符的行为,你需要提供一个__eq__方法的实现。如果你不覆盖它,那么默认的行为是检查对象是否真的是同一个对象,而在这种情况下它们并不是。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接