Sep-30-2021, 10:18 PM
(This post was last modified: Sep-30-2021, 10:18 PM by deanhystad.)
If you define the math functions you may as well make them generally useful. I would do something like this:
Though this is a silly program it aspires to do "good design" things like separating the implementation from the interface. add(a, b) knows how to compute a + b. It should not have to know about how results are displayed (there should not be a print). execute(op, a, b) does not know how to do any operations, but it knows how to find the right function for the operator. solve(equation) does not know anything about math, but it knows how to parse an equation and display the results. When you design code you should look for this kind of division of labor. Every function should do one thing that is easily described with a sentence or two. If you cannot describe what a function does you need to "refactor" your code to have functions that are well defined.
#calculator class with arithmetic methods class calc(): def solve(self, equation): '''Solve eqation in the form a op b where b is in "+-*/"''' a, op, b = equation.split() print(equation, '=', self.execute(op, float(a), float(b))) def execute(self, op, a, b): '''Return result of binary math operation''' if op == "+": return self.add(a, b) if op == "-": return self.sub(a, b) if op == "*": return self.mul(a, b) if op == "/": return self.div(a, b) raise ValueError(f'{op} is not a recognized operator') def add(self, a, b): '''Return a + b''' return a + b def sub(self, a, b): '''Return a - b''' return a - b def mul(self, a, b): '''Return a * b''' return a * b def div(self, a, b): '''Return a / b''' return a / b cal = calc() cal.solve('6 / 3') print(cal.execute('*', 2, 3))If we pretend that the calculator has support for more interesting operations, making those operations visible outside the calculator changes it from an application to a library. Your code exposed the operations, but not in a generically useful way. If I am using your library I probably want the div function to return the quotient instead of None.
Though this is a silly program it aspires to do "good design" things like separating the implementation from the interface. add(a, b) knows how to compute a + b. It should not have to know about how results are displayed (there should not be a print). execute(op, a, b) does not know how to do any operations, but it knows how to find the right function for the operator. solve(equation) does not know anything about math, but it knows how to parse an equation and display the results. When you design code you should look for this kind of division of labor. Every function should do one thing that is easily described with a sentence or two. If you cannot describe what a function does you need to "refactor" your code to have functions that are well defined.