Command Palette

Search for a command to run...

Hectal
Phase 8: Object-Oriented Python
Python · Exercise 4 of 6 PreviousNext
Intermediate

A Money class with special methods

Write a class Money(amount, currency) with __repr__ that gives text like Money(5, 'INR').

Add __eq__ (equal when amount and currency match), __hash__ (so equal values work in a set) and __add__ that returns a new Money for the same currency.

Adding different currencies must raise TypeError: return NotImplemented from __add__.

What Check tests

  1. repr(Money(5, 'INR')) is "Money(5, 'INR')"
  2. Equal values are equal, different ones are not
  3. Equal values collapse in a set
  4. Adding the same currency gives a new Money
  5. Adding different currencies raises TypeError
  6. Adding a non-Money value raises TypeError and comparing to one is False

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.