等于支持自建的Fraction类

时间:2017-05-16 13:45:08

标签: python class operators

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 个答案:

答案 0 :(得分:3)

试试这个:

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)

我希望它有所帮助。

答案 1 :(得分:2)

data model指定 operator domain: _ * _ list operand: _ * (int * (int * 'Z) list) 作为实施__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)方法的内容,以便它甚至可以比较倍数。

答案 2 :(得分:1)

在python中获取==运算符的自定义行为,您必须为方法__eq__提供实现。如果你不覆盖它,默认行为是检查对象是否真的是同一个对象,在这种情况下它们不是。