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 __truediv__(self, r):
return Rational(self.p * r.q, self.q * r.p)
def __str__(self):
return '%s/%s' % (self.p, self.q)
__repr__ = __str__
r1 = Rational(1, 3)
print(r1)
r2 = Rational(7, 6)
r3 = r1 + r2
print(r2)
print(r3)
print(r1 - r2)
r3 = r1 / r2
print(r3)
这里有点像C++的运算符重载。
要注意:
https://stackoverflow.com/questions/40770632/typeerror-unsupported-operand-types-for
Python3 uses special division names: __truediv__
and __floordiv__
for the /
and //
operators, respectively.