a wei
a wei

Reputation: 85

Python create built-in method for class

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

Upvotes: 0

Views: 303

Answers (1)

user4815162342
user4815162342

Reputation: 155336

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

Upvotes: 1

Related Questions