I am trying to override the __iadd__
method in python with fractions, now this is what I did. Please could some one check to see if I did it right. I have this and this, but that's not what I want. It should be used from a class
perspective.
My __iadd__
code:
def __iadd__(self, other):
"""
Implementation of the '+='
augmented function
:param other:
:return:
"""
newnum = self.num * other.den + self.den * other.num
newden = self.den * other.den
v = Fraction(newnum, newden)
return v
This is done in a class Fraction
with this structure:
def gcd(m, n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
class Fraction:
# initializing variables for class
def __init__(self, top, bottom):
# check if entered fraction is an integer
if isinstance(top, int) and isinstance(bottom, int):
# reduce the given fractions to lowest term
common = gcd(top, bottom)
self.num = abs(top) // common
self.den = abs(bottom) // common
else:
raise "Please only integers are allowed"
def __str__(self):
return str(self.num) + "/" + str(self.den)
This actually return the write value when done like this:
f1 = Fraction(1, 2)
f2 = Fraction(8, 10)
f1 += f2
print(f1)
Also did it by calling an overridden __add__
method:
def __iadd__(self, other):
"""
Implementation of the '+='
augmented function
:param other:
:return:
"""
if other == 0:
return self
else:
return self.__add__(other)
The overridden __add__
:
def __add__(self, otherfraction):
newnum = self.num * otherfraction.den + self.den * otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum, newden)