1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| 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): if not isinstance(top, int) or not isinstance(bottom, int): raise Exception("top or bottom of Fraction is not int type!") common = gcd(top,bottom) self.num = top//common self.den = bottom//common
def __str__(self): return str(self.num)+"/"+str(self.den)
def show(self): print(self.num,"/",self.den)
def __add__(self,other): newnum = self.num*other.den + \ self.den*other.num newden = self.den * other.den return Fraction(newnum,newden)
def __eq__(self, other): firstnum = self.num * other.den secondnum = other.num * self.den
return firstnum == secondnum def getNum(self): return self.num def getDen(self): return self.den def __sub__(self, other): newnum = self.num*other.den - \ other.num*self.den newden = self.den * other.den return Fraction(newnum, newden) def __mul__(self, other): return Fraction(self.num*other.num, self.den*other.den) def __truediv__(self, other): return Fraction(self.num*other.den, self.den*other.num) def __gt__(self, other): if self.num*other.den > self.den*other.num: return True else: return False def __ge__(self, other): if self.num*other.den >= self.den*other.num: return True else: return False def __lt__(self, other): if self.num*other.den < self.den*other.num: return True else: return False def __le__(self, other): if self.num*other.den < self.den*other.num: return True else: return False def __ne__(self, other): if self.num*other.den != self.den*other.num: return True else: return False def __radd__(self,other_int): """ Python will first try (4).__add__(myobj), and if that returns NotImplemented Python will check if the right-hand operand implements __radd__, and if it does, it will call myobj.__radd__(4) rather than raising a TypeError. """ newnum = self.num + \ self.den*other_int return Fraction(newnum,self.den) def __iadd__(self, other): """a = iadd(a, b) is equivalent to a += b.""" newnum = self.num*other.den + \ self.den*other.num newden = self.den * other.den return Fraction(newnum, newden) def __repr__(self): """ In short, the goal of __repr__ is to be unambiguous and __str__ is to be readable. 也就是说,__repr__是用于输出更多的关于对象的信息的,而__str__是为了print好看的。 """ return "num:{}, den:{}".format(self.num, self.den)
|