分数类:如何定义一个函数将分数加到整数中?

2024-10-08 22:27:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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。你知道吗


Tags: 答案selfreturndefnum分数class课程
2条回答

x + 11作为other参数触发__add__

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

Fraction() + 3  # prints 3

在你的__add__中,你要求other.den。因为other1,所以这不起作用。你知道吗

调查你的问题我想你需要做的是

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

那就试试吧

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

两者都能奏效

要解释它的工作原理需要一整本书。你知道吗

相关问题 更多 >

    热门问题