def gcd(m, n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
def show(self):
print(self.num, "/", self.den)
def __str__(self):
# 返回字符串形式的分数
return str(self.num) + "/" + str(self.den)
def __add__(self, otherfraction):
# 两个分数相加
newnum = self.num * otherfraction.den + self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)
def __sub__(self, otherfraction):
# 两个分数相减
newnum = self.num * otherfraction.den - self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)
def __mul__(self, otherfraction):
# 两个分数相乘
newnum = self.num * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)
def __truediv__(self, otherfraction):
# 两个分数相除
newnum = self.num * otherfraction.den
newden = self.den * otherfraction.num
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)
def __eq__(self, other):
# 判断两个分数是否相等
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
def __lt__(self, other):
# 判断两个分数的大小
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum < secondnum
def __gt__(self, other):
# 判断两个分数的大小
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum > secondnum
myf=Fraction(3,5)
print(myf)
f1=Fraction(1,4)
f2=Fraction(1,2)
f3=f1+f2
f4=f1-f2
f5=f1/f2
f6=f1*f2
print(f3)
print(f4)
print(f5)
print(f6)
print(f1>f2)
print(f1<f2)
print(f1==f2)
3/5
3/4
-1/4
1/2
1/8
False
True
False
参考:
Object-Oriented Programming in Python: Defining Classes