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 ZeroDivisionError should be raised with a Cannot divide by zero message.
  • If either of the inputs cannot be converted to a number, a ValueError should be raised with an Invalid number input message.
  • If the operator is not a Number, a TypeError should be raised with an Operator must be a Number message.
  • Additionally, you should implement a custom exception, UnsupportedOperatorError that inherits from ValueError, with a message Unsupported 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
a=Number(10); b=Number(2); print(a+b); print(a/b);
12 5
a=Number(10); b=Number(0); print(a/b);
Cannot divide by zero
a=Number('ten'); b=Number(2); print(a+b);
Invalid number input
a=Number(10); b=Number(2); print(a**b);
Unsupported operator
a=Number(10); b=2; print(a+b);
Operator must be a Number
a = Number(10); b = Number(2); c = Number(a * b); print(c.value)
20
a = Number(10); b = Number(2); c = Number((a - b) ** 2); print(c.value)
Unsupported operator
 

Constraints

Time limit: 2 seconds

Memory limit: 512 MB

Output limit: 1 MB

To check your solution you need to sign in
Sign in to continue