python - __rsub__ 和 __rtruediv__ 带分数

标签 python math fractions magic-methods

我试图在我创建的名为 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/

相关文章:

python + matplotlib : how to insert more space between the axis and the tick labels in a polar chart?

math - 帮助构建一个 OBB,尝试用 3 个向量表示一个矩阵

python - 左上角的原点坐标系是什么阻止了这个方程式的工作?

c - 如何使用 Visualdsp++ 应用低搁置滤波器?

python - 如何在方程输出中保留分数

python - 如何实现自定义方法并将其与 SQLAlchemy 中的查询一起使用

python - 使用正则表达式解析 .srt 文件

math - 使用推理规则证明逻辑运算

c - 反转长 double 的指数给了我一个疯狂的结果

python - 对列表列表中的元素求和