面向过程->面向对象
?如何实现简单的计算器功能
如计算俩个数字的和差之类,我们需要数字numbe_a、数字number_b、运算符operator以及结果result
面向过程
class Operation: number_a = input ( "请输入第一个数字:" ) number_b = input ( "请输入第二个数字:" ) operator = input ( "请输入+ - * /的运算符:" ) result = 0 if operator = = "+" : result = number_a + number_b elif operator = = "-" : result = number_a - number_b elif operator = = "*" : result = number_a * number_b elif operator = = "/" and number_b ! = 0 : result = number_a / number_b print ( "最终结果:" + result) |
上述代码存在一下几个问题:
1、输入的number_a和number_b是str类型,需要给他们转换为number
2、输入的运算符有可能不在我们的需要范围内,这时候代码没有做校验
3、输入的number_a和number_b如果不可以转换为number类型该怎么处理?
4、逻辑层和业务层在同一个class中,耦合度较高
一般来说一个系统会有逻辑层和业务层,那么我们可以根据这个方面进行拆分
逻辑层
class Operation: def __init__( self , number_a, number_b, operator): self .number_a = float (number_a) self .number_b = float (number_b) self .operator = operator def operation( self ): result = 0 if self .operator = = "+" : result = self .number_a + self .number_b elif self .operator = = "-" : result = self .number_a - self .number_b elif self .operator = = "*" : result = self .number_a * self .number_b elif self .operator = = "/" and self .number_b ! = 0 : result = self .number_a / self .number_b else : print ( '存在输入错误!' ) return "最终结果:" + str (result) |
业务层
if __name__ = = '__main__' : try : your_number_a = input ( "请输入第一个数字:" ) your_number_b = input ( "请输入第二个数字:" ) your_operator = input ( "请输入+ - * /的运算符:" ) print (Operation(your_number_a, your_number_b, your_operator).operation()) except Exception as e: print ( '存在输入错误!' + e) |