Deviopath › Python

Money with Operator Overloading

Hard · Classes

Python turns operators into method calls: a + b runs a.__add__(b), a < b runs a.__lt__(b), and repr(a) runs a.__repr__(). If a method returns NotImplemented, Python tries the reflected method on the other operand (like b.__radd__(a)) and raises TypeError if nothing works.

Money should never be stored as a float, so Money(cents, currency) keeps whole cents. Implement:

- a + b: a new Money. Different currencies raise ValueError("currency mismatch: USD vs EUR") (left currency first).

- __radd__: 0 + money returns the money, so the built-in sum() works

- money * n and n * money for an int n. For anything else return NotImplemented.

- ==: equal when cents and currency match. Return NotImplemented for values that are not Money.

- <: compares cents. Different currencies raise the same ValueError. Now sorted() works.

- repr: like "<Money 12.50 USD>", always two decimals, and "<Money -0.05 USD>" for negatives. Build it with integer math (divmod), not floats.

The driver run_money(ops) is already written. It turns [cents, currency] lists into Money objects, runs each operation and returns the results or error messages.

Next: Validating Descriptor