0

I made a class that can do some fraction arithmetic. I change the built-in method of __add__, __sub__,__mul__,and __div__ so that it can do arithmetic with fractions. I can use it with the +, - , * , / symbols. My question is, what do I have to do to be able to use __iadd__ as +=.

class Fraction:
    def __init__(self,num,den):
        self.num = num
        self.den = den
    def __str__(self):
        return str(self.num)+" / "+str(self.den)

    def __add__(self,other):
        num = self.num * other.den + other.num * self.den
        den = self.den * other.den
        common = self.gcf(num,den)
        return Fraction(num/common , den/common)

    def __iadd__(self,other):
        self.num = self.num * other.den + other.num * self.den
        self.den = self.den * other.den
        common = self.gcf(self.num,self.den)
        self.num = self.num/common
        self.den = self.den/common
1
  • 1
    always subclass from object if you are using Python 2.x. Commented Apr 11, 2015 at 16:43

1 Answer 1

1

You are missing return self at the end of your __iadd__ implementation. Augmented assignment methods are allowed to return different instances, which is why return self is necessary.

In an unrelated note, you can reduce some code duplication by implementing addition in terms of in-place addition, like this:

def __add__(self, other):
    clone = Fraction(self.num, self.den)
    clone += other
    return clone
Sign up to request clarification or add additional context in comments.

5 Comments

Actually after looking at my code I realized that I did that on purpose; if you use += it doesn't return a number.
@william880513 That was likely the result of the bug explained in the first paragraph of my answer.
What I am trying to do is so that I can change the value of a fraction by doing fraction1 += fraction2, instead of fraction1.__iadd__(fraction2)
@william880513 ...and definining __iadd__ will accomplish exactly that — provided you remember to return self at the end of it. The suggestion for how to avoid code duplication in __add__ is just an aside.
link This explain why return self is necessary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.