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
。你知道吗
试试这个:
正如评论中指出的,没有必要实现
__ne__
。你知道吗编辑:根据此答案注释中的要求,这里有一个简化分数的方法。你知道吗
分数的简化意味着用最大公约数除两个数。正如在here中发布的,代码相当简单
希望对你有帮助。你知道吗
data model将
__eq__
指定为实现==
检查的方法。你知道吗__eq__
的一个非常简单的实现是:它对
Fraction(1, 2) == Fraction(1, 2)
有效,但对Fraction(1, 2) == Fraction(2, 4)
无效。你知道吗您需要修改
__eq__
方法的内容,这样它甚至可以比较倍数。你知道吗在python中,要获得==运算符的自定义行为,必须提供方法
__eq__
的实现。如果不重写它,默认行为是检查对象是否真的是同一个对象,而在本例中它们不是。你知道吗相关问题 更多 >
编程相关推荐