分数类:如何定义一个函数来向整数添加分数?

时间:2017-07-15 10:49:55

标签: python operator-overloading

我正在学习Python的分数类,并在下面提出一个问题:

class Fraction:

     def __add__(self, other):
         newnum = self.num * other.den + self.den * other.num
         newden = self.den * other.den
         return Fraction(newnum, newden)

     def __radd__(self, other_int):
         newnum = self.num + self.den * other_int
         return Fraction(newnum, self.den)

x = Fraction(1, 2)

当我写这篇文章时,我得到了正确答案(3/2):

print(1 + x)

但是当我写这篇文章时:

print(x + 1)

我收到了错误

AttributeError: 'int' object has no attribute 'den'

为什么print(1 + x)被正确打印,print(x + 1)是错误的?我怎样才能print(x + 1)得到答案3/2。

2 个答案:

答案 0 :(得分:3)

x + 1触发__add__ 1作为other参数:

class Fraction:
    def __add__(self, other):
        print(other)

Fraction() + 3  # prints 3

__add__中,您要求other.den。由于other1,因此无效。

答案 1 :(得分:0)

调查你的问题我认为你需要做的是

>>> x = Fraction(1, 2)
>>> y = Fraction(1, 0)

然后尝试

>>> x + y
>>> y + x

两者都可以使用

解释它的工作方式将需要整本书。