Python 中整数的运算符重载

0 投票
1 回答
1800 浏览
提问于 2025-04-18 01:42

我正在写一个程序,用来处理有理数的除法,但我希望它能处理分数。我想用1去除以1/3,但我的程序在处理整数时遇到了错误。我尝试了几种不同的方法把整数转换成有理数,但都没有成功。任何帮助或指导都非常感谢。

这是我一直收到的错误信息,它是代码底部一个断言语句的提示。

错误追踪(最近的调用在最前面): 文件 "E:\Python\Rational number extension excercise.py",第47行,在 assert 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."

1 个回答

2
 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 这个判断永远不会为真,因为当你在 Racional 上运行 __rdiv__ 方法时,self 总是一个 Racional 类型的对象。你应该去检查 param,也就是你除法运算的左边的那个数(在你的例子中是1)。

撰写回答