我想编写一个允许算术运算符的fraction类,但是当我定义div方法时,它似乎不能除法。
from math import gcd
class Fraction:
def __init__(self, n, d):
self.n = n
self.d = d
def __add__(self, other):
newn = self.n * other.d + self.d * other.n
newd = self.d * other.d
common = gcd(newn, newd)
return Fraction(newn/common, newd/common)
def __sub__(self, other):
newn = self.n * other.d - self.d * other.n
newd = self.d * other.d
common = gcd(newn, newd)
return Fraction(newn/common, newd/common)
def __div__(self, other):
newn = self.n * other.d
newd = self.d * other.n
common = gcd(newn, newd)
return Fraction(newn/common, newd/common)
def __mul__(self, other):
newn = self.n * other.n
newd = self.d * other.d
common = gcd(newn, newd)
return Fraction(newn/common, newd/common)
def __repr__(self):
return "{}/{}".format(int(self.n), int(self.d))
print(Fraction(1, 2) / Fraction(1, 4))
您需要在Python 3中使用__truediv__