【发布时间】: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