Python __带分数的rsub_uuuuu和rtruediv_uuu
我试图在我创建的名为Fraction的类中使用Python __带分数的rsub_uuuuu和rtruediv_uuu,python,math,fractions,magic-methods,Python,Math,Fractions,Magic Methods,我试图在我创建的名为Fraction的类中使用\uuu rsub\uuu函数 下面是分数类代码: 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
\uuu rsub\uuu
函数
下面是分数类代码:
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)
现在,如果我分别使用:return self+other
或return self*other
来执行\uuud\uud
或\urmul\uud
,它将执行所需的结果。但是,通过简单地更改运算符,执行\uuuuu rsub\uuuuu
和\uuuu rtruediv\uuuuuu
并不起作用。我怎样才能解决这个问题
本质上,调用函数的代码是:
f = Fraction(2,3)
g = Fraction(4,8)
print("2 - f: ", 2 - f)
print("2 / f: ", 2 / f)
谢谢你的帮助 您首先需要将
其他
转换为分数
,以实现此功能:
def __rsub__(self, other):
return Fraction(other, 1) - self
由于\uuu rsub\uuu()
仅在other
不是Fraction
类型时才会被调用,因此我们不需要任何类型检查——我们只是假设它是一个整数
当前的
\uuuu sub\uuuu()
实现也需要一些工作——如果other
没有Fraction类型,它将不返回任何内容。您首先需要将other
转换为Fraction
,以实现此功能:
def __rsub__(self, other):
return Fraction(other, 1) - self
由于\uuu rsub\uuu()
仅在other
不是Fraction
类型时才会被调用,因此我们不需要任何类型检查——我们只是假设它是一个整数
\uuu sub\uuu()
的当前实现也需要一些工作——如果other
没有类型france
,它将不返回任何内容,因为您键入了check,并且当第二个操作数不是france
时返回None
(另外,如果isinstance(…):
,如果isinstance(…),则返回,如果isinstance(…)==真:
)。您需要强制该参数。因为您键入了check,当第二个操作数不是分数时返回None
(另外,如果isinstance(…):
,如果isinstance(…)==True,则返回)。您需要强制执行参数。实现“r”操作的常用方法是1)检查以确保其他类型是您知道如何处理的类型2)如果不是,则返回NotImplemented;3)如果是,则转换为无法与自身交互的类型:
def __radd__(self, other):
if not instance(other, (int, Fraction):
return NotImplemented
converted = Fraction(other)
return converted + self
实现“r”操作的常用方法是1)检查以确保其他类型是您知道如何处理的类型2)如果不是,则返回NotImplemented;3)如果是,则转换为可以与自身交互的类型:
def __radd__(self, other):
if not instance(other, (int, Fraction):
return NotImplemented
converted = Fraction(other)
return converted + self
请不要写==True
!请不要写==True
!谢谢你的提醒。我已经做了调整:)谢谢你提醒我。我已经做了调整:)