- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我试图在我创建的名为 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 + other
或 return 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/
考虑以下代码片段: import numpy as np class MyClass: def __rsub__(self, other): print(type(other)
在通过像 __rsub__ 这样的右手运算符传递 numpy 数组后,如何访问它的属性? 我用 python 写了一个非常简单的类,它定义了两个函数: class test(object):
我试图在我创建的名为 Fraction 的类中使用 __rsub__ 函数。 这是分数类代码: def __init__(self, num, denom): ''' Creates a ne
当我遇到 __rsub__ 时,我正在自学 Python方法。虽然我可以找到 explanation on the method in the official documentation : The
我是一名优秀的程序员,十分优秀!