# Enter a code
class Rational(object):
def __init__(self,p,q):
self.p = p
self.q = q
def __add__(self,r):
return Rational(self.p*r.q + self.q*r.p,self.q*r.q)
def __sub__(self,r):
return Rational(self.p*r.q - self.q*r.p,self.q*r.q)
def __mul__(self,r):
return Rational(self.p*r.p , self.q*r.q)
def __div__(self,r):
return Rational(self.p*r.q,self.q*r.p)
def __floordiv__(self,r):
return Rational(self.p*r.q,self.q*r.p)
def __str__(self):
return '{}/{}'.format(self.p,self.q)
a1 = Rational(1,5)
a2 = Rational(4,5)
print(a1 + a2)
print(a1 - a2)
print(a1*a2)
print(a1/a2)
print(a1//a2)
import sys
print(sys.version)
可以查看python版本不是3.X哦
def __truediv__(self,r):
return Rational(self.p*r.q,self.q*r.p)
地板除是向下取整,你的代码里是普通除法
def __div__(self,r):
return Rational(self.p*r.q,self.q*r.p)
def __floordiv__(self,r):
return Rational(self.p*r.q,self.q*r.p)