I’m trying to learn OOP in Python, and making the following code to overwrite the __plus__ method
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 # I want to result be 2/12
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'Fraction'
but it gives me an error, I don’t know how to solve the error, any idea?
You need to override the
__add__method instead of__plus__. Just try to replace__plus__with__add__.