— Tutorial, Python, Pattern — 1 min read
1import abc2
3
4class CalcCmdAbs(metaclass=abc.ABCMeta):5 def __init__(self, *args, **kwargs):6 self._args = args7 self._kwargs = kwargs8
9 @property10 @abc.abstractmethod11 def name(self):12 raise NotImplemented()13
14 def execute(self):15 raise NotImplemented()
1from .interface import CalcCmdAbs2
3OPERATORS = list()4
5
6def register_operator(cls):7 OPERATORS.append(cls)8 return cls9
10
11@register_operator12class AddCmd(CalcCmdAbs):13 name = "add"14
15 def __init__(self, a, b):16 super().__init__(a, b)17 self.a = a18 self.b = b19
20 def execute(self):21 return self.a + self.b22
23
24@register_operator25class SubtractCmd(CalcCmdAbs):26 name = "subtract"27
28 def __init__(self, a, b):29 super().__init__(a, b)30 self.a = a31 self.b = b32
33 def execute(self):34 return self.a - self.b35
36
37class NoneCmd(CalcCmdAbs):38 name = "None Command"39
40 def execute(self):41 print("Invalid Command")
1from .commands import OPERATORS, NoneCmd2
3
4def get_commands() -> dict:5 return dict([cmd.name, cmd] for cmd in OPERATORS)6
7
8def parse_commands(commands: dict, operation: str, *args):9 command = commands.setdefault(operation, NoneCmd)10 return command(*args)
1import unittest2
3from .utils import get_commands, parse_commands4
5
6class TestCase(unittest.TestCase):7
8 def setUp(self) -> None:9 self.commands = get_commands()10
11 def test_addition(self):12 command = parse_commands(self.commands, "add", 1, 1)13 self.assertEqual(command.execute(), 2, "Addition fail")14
15 def test_subtraction(self):16 command = parse_commands(self.commands, "subtract", 1, 1)17 self.assertEqual(command.execute(), 0, "Subtraction fail")