Advertisement
fkudinov

Python Framework: Calculator

Nov 20th, 2024
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | Source Code | 0 0
  1. from numbers import Complex
  2.  
  3.  
  4. class Calc:
  5.  
  6.     OPERATIONS = {"add": lambda a, b: a + b,
  7.                   "sub": lambda a, b: a - b,
  8.                   "mul": lambda a, b: a * b,
  9.                   "div": lambda a, b: a / b}
  10.  
  11.     @classmethod
  12.     def calculate(cls, a: Complex, b: Complex,
  13.                   operation: str = "add",
  14.                   key: callable = None):
  15.  
  16.         print(f"Calculate: {a} and {b}, "
  17.               f"operation: {operation if not key else key.__name__}")
  18.  
  19.         assert isinstance(a, Complex)
  20.         assert isinstance(b, Complex)
  21.  
  22.         func = key if key is not None else cls.OPERATIONS[operation]
  23.         res = func(a, b)
  24.  
  25.         print(f"Result: {res}")
  26.  
  27.         return res
  28.  
  29.     @classmethod
  30.     def run(cls):
  31.  
  32.         while True:
  33.             msg = input("operation, a, b: ")
  34.             operation, a, b = map(str.strip, msg.split(","))
  35.             a = complex(a) if "j" in a else float(a)
  36.             b = complex(b) if "j" in b else float(b)
  37.             cls.calculate(a, b, operation)
  38.             print("======================================")
  39.  
  40.     @classmethod
  41.     def register(cls, name: str):
  42.  
  43.         def add_to_registry(func: callable):
  44.  
  45.             assert name not in cls.OPERATIONS
  46.             cls.OPERATIONS[name] = func
  47.             return func
  48.  
  49.         return add_to_registry
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement