Advertisement
fkudinov

Python Framework: Calculator

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