为什么除(__truediv__)不行,加,减,乘都可以
# Enter a code
class Rational(object):
def __init__(self, p, q):
self.p = p
self.q = q
#add
def __add__(self, r):
return Rational(self.p * r.q + self.q * r.p, self.q * r.q)
#sub
def __sub__(self,r):
if self.p * r.q > self.q * r.p:
return Rational(self.p * r.q - self.q * r.p,self.q *r.q)
if self.q * r.p > self.p * r.q:
return Rational(self.q * r.p - self.p * r.q,self.q *r.q)
#mul
def __mul__(self,r):
return Rational(self.p * r.p , self.q * r.q)
#div
def __truediv__(self,r):
return Rational(self.p * r.q ,self.q * r.p)
def __repr__(self):
return '{}/{}'.format(self.p,self.q)
#example
r1 = Rational(1,2)
r2 = Rational(2,3)
#add
print(r1 + r2)
#sub
print(r1 - r2)
#mul
print(r1 * r2)
print(r1 / r2)