Creating a Custom Calculator
Your task is to create a Number class that utilizes Python's magic methods (__add__, __sub__, __mul__, __truediv__) to perform mathematical operations. However, the class needs to be robust and be able to handle various exceptions that can occur during these operations:
If a division by zero is attempted, a
ZeroDivisionErrorshould be raised with aCannot divide by zeromessage.If either of the inputs cannot be converted to a number, a
ValueErrorshould be raised with anInvalid number inputmessage.If the operator is not a
Number, aTypeErrorshould be raised with anOperator must be a Numbermessage.Additionally, you should implement a custom exception,
UnsupportedOperatorErrorthat inherits fromValueError, with a messageUnsupported operator. This error should be raised if an operation is attempted that is not supported by the class. That includes__floordiv__,__mod__,__pow__,__lshift__,__rshift__,__and__,__xor__,__or__.
All of the valid magic methods should return a Number object.
Note: Don’t forget to implement the __str__ magic method to return the value of the Number.
Input | Output |
| 12 |
| Cannot divide by zero |
| Invalid number input |
| Unsupported operator |
| Operator must be a Number |
| 20 |
| Unsupported operator |
Constraints
Time limit: 2 seconds
Memory limit: 512 MB
Output limit: 1 MB