How do I implement addition and multiplication for a custom Fraction class?

0
0
Asked By MellowPine42 On

I'm building a calculator that behaves like I do by hand, so I'm writing my own Fraction class instead of using the standard fraction library. I want to support adding and multiplying two Fraction objects, as well as combining a Fraction with ordinary integers. I also don't want the class to automatically reduce or simplify the resulting fractions. What should __add__, __radd__, and __mul__ look like?

3 Answers

Answered By CedarFox19 On

For an integer on the left, such as 3 + my_fraction, Python first tries int.__add__. Since int does not know how to add your class, Python can fall back to your Fraction.__radd__ method. The easiest implementation is to make __radd__ point to __add__, because addition is commutative. You can use the same idea for other reflected operators when the order is equivalent.

MellowPine42 -

So __radd__ is the part needed for int + Fraction, while Fraction + int uses __add__ directly.

Answered By BrightKite7 On

Python calls the left operand’s __add__ method when you write a + b. Your method should calculate the new numerator and denominator, then return a new Fraction rather than changing either existing object. For two fractions, addition can use a common denominator: (a/b) + (c/d) becomes (a*d + c*b)/(b*d). If the other value is an int, treat it as a fraction with denominator 1. Multiplication is simpler: multiply the numerators and denominators directly. Return NotImplemented for unsupported types so Python can try the reflected operation.

MellowPine42 -

That makes sense—I initially assumed the operation would modify the left-hand Fraction, but returning a new object is cleaner.

Answered By OrbitingMaple8 On

A basic structure could look like this:nnclass Fraction:n def __init__(self, numerator, denominator):n self.numerator = numeratorn self.denominator = denominatornn def __add__(self, other):n if isinstance(other, int):n other = Fraction(other, 1)n if not isinstance(other, Fraction):n return NotImplementedn return Fraction(n self.numerator * other.denominator + other.numerator * self.denominator,n self.denominator * other.denominatorn )nn __radd__ = __add__nn def __mul__(self, other):n if isinstance(other, int):n other = Fraction(other, 1)n if not isinstance(other, Fraction):n return NotImplementedn return Fraction(n self.numerator * other.numerator,n self.denominator * other.denominatorn )nn __rmul__ = __mul__nnThis deliberately leaves fractions unsimplified. You may also want to reject a zero denominator in __init__, and later add methods such as __str__ for readable output.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.