【问题标题】:Fraction class: How can define a function to add a fraction to an integer? [closed]分数类:如何定义一个将分数添加到整数的函数? [关闭]
【发布时间】:2017-07-15 10:49:54
【问题描述】:

我正在学习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。

【问题讨论】:

  • 请正确格式化并给我们足够的类来尝试这个(至少缺少构造函数)。
  • 提问前需要做OOP功课。谷歌python oop。
  • Put 1 as Fraction(1,1) 你也可以在你的类中指定当 self 或 other 是 int 类型时将其转换为 Fraction 对象。
  • other 是一个int (1),而您要求other.den'int' object has no attribute 'den'.
  • 原谅我,这是我的第一次编辑。我本来可以给你看所有代码的(有点长),还是谢谢你。

标签: python operator-overloading


【解决方案1】:

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

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

Fraction() + 3  # prints 3

在您的__add__ 中,您要求other.den。由于other1,所以这是行不通的。

【讨论】:

  • so,如果我想将1/2加到1,如何在Fraction类中定义函数?(我已经做了def __add__(self, other):newnum = self.num * other .den + self.den * other.num newden = self.den * other.den return Fraction(newnum, newden)),谢谢。
【解决方案2】:

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

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

那就试试

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

两者都可以

解释它的工作原理需要整本书。

【讨论】:

猜你喜欢
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多