我试图制作自己的Fraction课程'。
几乎所有代码都可以正常工作,但在/
,>
,<
,这些代码无效。
我不知道我的代码有什么问题。
def gcd(m, n):
while m%n != 0:
m, n = n, m%n
return n
class Fraction:
'''Fractional class'''
def __init__(self, num, denom):
self.num = num
self.denom = denom
def __str__(self):
return str(self.num)+'/'+str(self.denom)
def __add__(self, other):
new_num = self.num * other.denom + other.num * self.denom
new_denom = self.denom * other.denom
common = gcd(new_num, new_denom)
return Fraction(new_num//common, new_denom//common)
def __sub__(self, other):
new_num = self.num * other.denom - other.num * self.denom
new_denom = self.denom * other.denom
common = gcd(new_num, new_denom)
return Fraction(new_num//common, new_denom//common)
def __mul__(self, other):
new_num = self.num * other.num
new_denom = self.denom * other.denom
common = gcd(new_num, new_denom)
return Fraction(new_num//common, new_denom//common)
def __div__(self, other):
new_num = self.num * other.denom
new_denom = self.denom * other.num
common = gcd(new_num, new_denom)
return Fraction(new_num//common, new_denom//common)
def __equal__(self, other):
return (self.num * other.denom) == (other.num * self.denom)
def __big__(self, other):
return str(self.num * other.denom) > str(other.num * self.denom)
def __small__(self, other):
return self.num * other.denom < other.num * self.denom
if __name__ == "__main__":
f1 = Fraction(1,4)
f2 = Fraction(1,2)
print(f1+f2)
print(f1 - f2)
print(f1 * f2)
print(f1 / f2) #not working
print(f1 == f2)
print(f1 > f2) #not working
print(f1 < f2) #not working
我得到以下输出:
3/4
-1/4
1/8
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-50-50cad0951bd1> in <module>()
57 print(f1 - f2)
58 print(f1 * f2)
---> 59 print(f1 / f2) #not working
60
61 print(f1 == f2)
TypeError: unsupported operand type(s) for /: 'Fraction' and 'Fraction'
我是否正确定义了__div__
?
答案 0 :(得分:2)
Python 3.x使用__truediv__
和__floordiv__
。 __div__
用于python 2.x。
要进行比较工作,您需要定义__lt__
,__gt__
,__ge__
和__le__
。