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

September 23, 2026 3 answers
Asked by 8mm.film.reel
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?

Answers

+5 missing semicolons
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.
Reply to this answer
stencil_209
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.

8mm.film.reel: That makes senseโ€”I initially assumed the operation would modify the left-hand Fraction, but returning a new object is cleaner.

Reply to this answer
griddle season
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.

8mm.film.reel: So __radd__ is the part needed for int + Fraction, while Fraction + int uses __add__ directly.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions