1

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' 
1
  • 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) Commented May 24, 2019 at 15:47

1 Answer 1

3

Try this

f1 = Fraction(1, 2) f2 = Fraction(2, 3) print(f1 * f2) 

Here I'm

  • Creating an object f1 of class Fraction this is 1/2
  • Similarly f2 which is 2/3
  • Now f1 * f2 automatically calls the dunder method __mul__ of f1 with f2 as the other argument
  • So you should see the expected Fraction object getting printed

PS: The reason why you're getting the AttributeError is because, __mul__ expects Fraction objects to be passed - while you are passing ints

Sign up to request clarification or add additional context in comments.

3 Comments

print(f1 * f2)
@DeveshKumarSingh fixed
Thanks, I can see my mistake now, is much easier doing this way :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.