Build a Fraction Class
Advanced · Write the code · from Python Operator Overloading: Make Classes Work with +, -, ==
From the lesson: Python Operator Overloading: Make Classes Work with +, -, ==
The + operator means different things in different contexts. 3 + 5 gives you 8. 'hello' + ' world' gives you 'hello world'. [1, 2] + [3, 4] gives you [1, 2, 3, 4]. Same symbol, completely different behavior.
Read the lessonCreate a Fraction class with num (numerator) and den (denominator). Add __add__ that adds two fractions using the formula (a/b + c/d = (a*d + c*b) / (b*d)). Add __eq__ that checks if two fractions are equal by cross-multiplying (a/b == c/d when a*d == b*c). Add __repr__ returning '<num>/<den>'. Create Fraction(1, 2) and Fraction(1, 3), add them, and print the result. Then print whether Fraction(1, 2) == Fraction(2, 4).
More Operator Overloading exercises
- Add Two Points TogetherBeginner
- Scale a Vector with MultiplicationIntermediate
- Fix the Broken __iadd__Intermediate
- Predict the Operator OutputIntermediate
- Refactor Methods to OperatorsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz