[英]Operator overloading with integers Python
我正在編寫一個程序來划分有理數,但我希望它能夠處理分數。 我想將1除以1/3但我的程序在處理整數時遇到錯誤。 我試圖將整數轉換為合理的幾種不同的方式,但沒有任何作用。 任何幫助或指導將不勝感激。
這是我一直收到的錯誤,它是代碼底部的assert語句的標志。
回溯(最近一次調用最后一次):文件“E:\\ Python \\ Rational數字擴展名excercise.py”,第47行,斷言Rational(3)== 1 / r3,“除法測試失敗。” TypeError:/:'int'和'Rational'的不支持的操作數類型
class Rational(object):
""" Rational with numerator and denominator. Denominator
parameter defaults to 1"""
def __init__(self,numer,denom=1):
#test print('in constructor')
self.numer = numer
self.denom = denom
def __truediv__(self,param):
'''divide two rationals'''
#test print('in truediv')
if type(param) == int: # convert ints to Rationals
param = Rational(param)
if type(param) == Rational:
# find a common denominator (lcm)
the_lcm = lcm(self.denom, param.numer)
# adjust the param value
lcm_numer = (the_lcm * param.numer)
lcm_denom = (the_lcm * param.denom)
true_param = int(lcm_denom / lcm_numer)
#print(int(lcm_denom / lcm_numer))
# multiply each by the lcm, then multiply
numerator_sum = (the_lcm * self.numer/self.denom) * (true_param)
#print(numerator_sum)
#print(Rational(int(numerator_sum),the_lcm))
return Rational(int(numerator_sum),the_lcm)
else:
print('wrong type') # problem: some type we cannot handle
raise(TypeError)
def __rdiv__(self,param):
'''divide two reversed rationals'''
# mapping is correct: if "(1) / (x/x)", 1 maps (to 1/1)
if type(self) == int:
self.numer = self
self.denom = 1
return self.__truediv__(self.numer)
return self.__truediv__(self.denom)
r1 = Rational(2,3)
r2 = Rational(1,4)
r3 = Rational(1,3)
assert Rational(2) == r1 / r3, "Division test failed."
assert Rational(3) == 1 / r3, "Division test failed."
def __rdiv__(self,param):
'''divide two reversed rationals'''
# mapping is correct: if "(1) / (x/x)", 1 maps (to 1/1)
if type(self) == int:
self.numer = self
self.denom = 1
type(self) == int
將永遠不會計算為True:如果你正在運行__rdiv__
在Racional
,自我永遠是Racional
。 你會想要測試param
,它是除法的左側(在你的例子中為1)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.