gpt4 book ai didi

python - __rsub__ 和 __rtruediv__ 带分数

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:14 28 4
gpt4 key购买 nike

我试图在我创建的名为 Fraction 的类中使用 __rsub__ 函数。

这是分数类代码:

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 + otherreturn self * other分别,它将执行所需的结果。但是,__rsub____rtruediv__ 不能通过简单地更改运算符来工作。我该如何解决这个问题?

本质上,调用函数的代码是:

f = Fraction(2,3)
g = Fraction(4,8)
print("2 - f: ", 2 - f)
print("2 / f: ", 2 / f)

感谢您的帮助!

最佳答案

您首先需要将 other 转换为 Fraction 以使其工作:

def __rsub__(self, other):
return Fraction(other, 1) - self

因为 __rsub__() 只有在 other 不是 Fraction 类型时才会被调用,所以我们不需要任何类型检查——我们只是假设它是一个整数。

您当前的 __sub__() 实现还需要做一些工作——如果 other 的类型不是 Fraction,它不会返回任何内容。

关于python - __rsub__ 和 __rtruediv__ 带分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8012772/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com