等于对自建分数类的支持

2024-09-22 16:33:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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。你知道吗


Tags: andoftheselfforreturndefbe
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)

希望对你有帮助。你知道吗

data model__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__方法的内容,这样它甚至可以比较倍数。你知道吗

在python中,要获得==运算符的自定义行为,必须提供方法__eq__的实现。如果不重写它,默认行为是检查对象是否真的是同一个对象,而在本例中它们不是。你知道吗

相关问题 更多 >