【问题标题】:Operator overloading with integers Python使用整数 Python 重载运算符
【发布时间】:2014-04-07 13:30:51
【问题描述】:

我正在编写一个程序来划分有理数,但我希望它能够处理分数。我想将 1 除以 1/3,但我的程序在处理整数时遇到错误。我试图通过几种不同的方式将整数转换为有理数,但没有任何效果。任何帮助或指导将不胜感激。

这是我不断收到的错误,它是代码底部断言语句中的标志。

Traceback(最近一次调用最后一次): 文件“E:\Python\Rational number extension 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."

【问题讨论】:

  • 你能提供一个失败的测试用例吗? “遇到麻烦”是什么意思?
  • 您使用的是哪个版本的Python?您已标记3.x。在最新版本的 Python (3.x) 中,除以两个 ints 将自动生成 float。在您的情况下,由于类型提升,将int 除以float 也应该导致float。您能否举例说明您遇到的问题?
  • “遇到麻烦”是指程序中的断言语句不允许我将整数(示例中为 1)除以有理数(示例中为 1/3)。我正在使用 python 3.3.4。程序中没有使用类型提升,因为我将数字划分为就好像它们是分数一样。 (3/3) / (1/ 3) = 3

标签: python python-3.x integer operator-overloading rational-numbers


【解决方案1】:
 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:如果您在 Racional 上运行 __rdiv__,则 self 将始终是 Racional。您需要测试 param,它是除法的左侧(在您的示例中为 1)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-05
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多