我正在尝试在 Python 中学习 OOP,并制作以下代码来覆盖该__plus__
方法
class Fraction(object):
'''Define a fraction type'''
def __init__(self, num=0, denom=1):
'''Create a new Fraction with numerator num and denominator demon'''
self.numerator = num
if denom != 0:
self.denominator = denom
else:
raise ZeroDivisionError
def __plus__(self, f):
num = self.numerator + f.numerator
denom = self.numerator + f.denominator
return "{0}/{1}".format(num, denom)
f = Fraction(1, 6)
print f + f # 我希望结果是 2/12
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'Fraction'
但它给了我一个错误,我不知道如何解决这个错误,知道吗?