__rsub__ 和 __rtruediv__ 与分数
我正在尝试在我自己创建的一个叫做Fraction的类中使用__rsub__
这个函数。
这是Fraction类的代码:
def __init__(self, num, denom):
''' Creates a new Fraction object num/denom'''
self.num = num
self.denom = denom
self.reduce()
def __repr__(self):
''' returns string representation of our fraction'''
return str(self.num) + "/" + str(self.denom)
def reduce(self):
''' converts our fractional representation into reduced form'''
divisor = gcd(self.num, self.denom)
self.num = self.num // divisor
self.denom = self.denom // divisor
def __sub__(self, other):
if isinstance(other,Fraction) == True:
newnum = self.num * other.denom - self.denom*other.num
newdenom = self.denom * other.denom
return Fraction(newnum, newdenom)
现在,如果我使用__radd__
或者__rmul__
,通过写return self + other
或者return self * other
,它们都能正常工作,得到我想要的结果。不过,使用__rsub__
和__rtruediv__
时,仅仅改变操作符并不能正常工作。我该怎么解决这个问题呢?
基本上,调用这些函数的代码是:
f = Fraction(2,3)
g = Fraction(4,8)
print("2 - f: ", 2 - f)
print("2 / f: ", 2 / f)
谢谢你们的帮助!
3 个回答
0
实现一个“r”操作的常见方法是:第一步,检查一下other是不是你知道怎么处理的类型;第二步,如果不是,就返回一个“未实现”的提示;第三步,如果是的话,就把它转换成一个可以和自己互动的类型:
def __radd__(self, other):
if not instance(other, (int, Fraction):
return NotImplemented
converted = Fraction(other)
return converted + self
1
因为你在检查类型的时候,如果第二个操作数不是 Fraction
,就返回 None
(另外,使用 if isinstance(...):
,而不是 if isinstance(...) == True:
)。你需要把这个参数转换成正确的类型。
3
你首先需要把 other
转换成 Fraction
,这样才能让这个功能正常工作:
def __rsub__(self, other):
return Fraction(other, 1) - self
因为 __rsub__()
这个方法只有在 other
不是 Fraction
类型的时候才会被调用,所以我们不需要检查类型——我们可以直接假设它是一个整数。
你现在的 __sub__()
方法也需要改进——如果 other
不是 Fraction
类型,它就什么都不返回。