class Rational:
def __init__(self,num,den=1): # 初始化方法,构造本类的新对象
self.num = num
self.den = den
def plus(self,another): # 实例方法
den = self.den * another.den
num = (self.num*another.den+self.den*another.num)
return Rational(num,den)
def print(self): # 实例方法
print(str(self.num)+"/"+str(self.den))
class Rational_2:
@staticmethod
def _gcd(m,n):
if n==0:
m,n = n,m
while m!=0:
m,n = n%m , m
return n
def __init__(self,num,den=1):
if not isinstance(num,int) or not isinstance(den,int):
raise TypeError
if den == 0:
raise ZeroDivisionError
sign = 1
if num<0:
num,sign = -num,-sign
if den<0:
den,sign = -den,-sign
# call function gcd defined in this class
g = Rational_2._gcd(num,den)
self._num = sign*(num//g)
self._den = den//g
def num(self):
return self._num
def den(self):
return self._den
def __add__(self, another): # mimic+operator
if not isinstance(another,Rational_2):
raise TypeError
den = self._den * another.den()
num = (self._num * another.den() + self._den*another.num())
return Rational_2(num,den)
def __mul__(self, another): # mimic * operator
if not isinstance(another,Rational_2):
raise TypeError
return Rational_2(self._num*another.num(),self._den*another.den())
def __floordiv__(self, another): # mimic // operator
if not isinstance(another,Rational_2):
raise TypeError
if another.num() == 0:
raise ZeroDivisionError
return Rational_2(self._num*another.den(),self._den*another.num())
def __eq__(self, another):
return self._num*another.den() == self._den * another.num()
def __lt__(self, another):
return self._num * another.den() < self._den * another.num()
def __str__(self):
return str(self._num)+"/"+str(self._den)
def print(self):
print(self._num,"/",self._den)
five = Rational_2(5)
x = Rational_2(3,5)
x.print()
print("Two thirds are",Rational_2(2,3))
y = five+x*Rational_2(5,17)
y.print()