标签:index panel conf ora 设计模式 under 没有 double 代码
如计算俩个数字的和差之类,我们需要数字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) |
标签:index panel conf ora 设计模式 under 没有 double 代码
原文地址:https://www.cnblogs.com/CSgarcia/p/12711835.html