我正在学习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。你知道吗
x + 1
以1
作为other
参数触发__add__
:在你的
__add__
中,你要求other.den
。因为other
是1
,所以这不起作用。你知道吗调查你的问题我想你需要做的是
那就试试吧
两者都能奏效
要解释它的工作原理需要一整本书。你知道吗
相关问题 更多 >
编程相关推荐