我正在学习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。
答案 0 :(得分:3)
x + 1
触发__add__
1
作为other
参数:
class Fraction:
def __add__(self, other):
print(other)
Fraction() + 3 # prints 3
在__add__
中,您要求other.den
。由于other
为1
,因此无效。
答案 1 :(得分:0)
调查你的问题我认为你需要做的是
>>> x = Fraction(1, 2)
>>> y = Fraction(1, 0)
然后尝试
>>> x + y
>>> y + x
两者都可以使用
解释它的工作方式将需要整本书。