How do I make multiplication work with my class Fraction?
class Fraction(object): def __init__(self, num, den): self.num = num self.den = den def resolve(self): #a = 2 #b = 6 #c = 2 #d = 5 self.num = self.num / other.num self.den = self.den / other.den return self def __str__(self): return "%d/%d" %(self.num, self.den) def __mul__(self, other): den = self.den * other.num num = self.num * other.den return (Fraction(self.num * other.num, self.den * other.den)) print('Multiplication:', Fraction.__mul__(2, 6)) This is the output:
Traceback (most recent call last): File "app.py", line 43, in <module> print('Multiplication:', Fraction.__mul__(2, 6)) File "app.py", line 27, in __mul__ den = self.den * other.num AttributeError: 'int' object has no attribute 'den'
Fraction.__mul__(2, 6)is not an instance of the object. You have to initialize the Fraction object.Fraction(2,6).__mul__(Fraction(1,3)), but you don't even need to do that because you mul maps to the asterisk.Fraction(2,6) * Fraction(1,3)