Python 分数类:如何定义将分数添加到整数的函数?

Python 分数类:如何定义将分数添加到整数的函数?,python,operator-overloading,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)

我正在学习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”对象没有属性“den”
为什么print1+x打印正确,printx+1打印错误?如何打印X+1得到3/2的答案。

查看您的问题,我认为您需要做的是

>>> x = Fraction(1, 2)
>>> y = Fraction(1, 0)
然后试试看

>>> x + y
>>> y + x
两者都会起作用

要解释它是如何工作的,需要一整本书。

x+1触发器\uuuu添加\uuuuu,另一个参数为1:

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

Fraction() + 3  # prints 3

在你的“添加”中,你要求其他.den。因为另一个是1,所以这不能工作。

请正确设置格式,并给我们足够的类来尝试这一点,至少缺少构造函数。在提问之前,您需要做OOP作业。google python oop.Put 1为Fraction1,1当self或other的类型为int时,您还可以在类中指定将其转换为Fraction对象。other是int 1,并且您已请求other.denint'对象没有属性'den'。请原谅,这是我第一次编辑。我本可以给你看所有的代码,虽然有点长,但还是要谢谢你。你能告诉我们radd方法将如何以及何时触发吗?我也是一个像你一样的学习者。谢谢你教我。@RajanChahan我正在学习这本书,想解决问题7,所以,我有一个问题在上面:当右边的论点不支持添加类似的东西时,会调用radd。@Chris这里有一个很好的Reddit线程给你,所以,如果我想添加1/2到1,如何在类分数中定义函数?我已经做了def\uu add\uu self,other:newnum=self.num*other.den+self.den*other.num newden=self.den*other.den返回分数newnum,newden,谢谢。