简单工厂模式

2018-06-18 00:34:07来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 1 class Operation():
 2 
 3     def __init__(self, NumberA=0, NumberB=0):
 4         self.NumberA = NumberA
 5         self.NumberB = NumberB
 6 
 7     def GetResult(self):
 8         pass
 9 
10 
11 class AddOp(Operation):
12 
13     def GetResult(self):
14         return self.NumberB + self.NumberA
15 
16 
17 class MinusOp(Operation):
18 
19     def GetResult(self):
20         return self.NumberA - self.NumberB
21 
22 
23 class MultiOp(Operation):
24 
25     def GetResult(self):
26         return self.NumberA * self.NumberB
27 
28 
29 class DivideOp(Operation):
30 
31     def GetResult(self):
32         try:
33             return 1.0 * self.NumberA / self.NumberB
34         except ZeroDivisionError:
35             raise
36 
37 
38 class OperationFatory():
39 
40     def ChooseOperation(self, op):
41         if op == '+':
42             return AddOp()
43         if op == '-':
44             return MinusOp()
45         if op == '*':
46             return MultiOp()
47         if op == '/':
48             return DivideOp()
49 
50 
51 if __name__ == '__main__':
52     ch = ''
53     while not ch == 'q':
54         NumberA = float(input('Please input number1:  '))
55         op = input('Please input the operation:  ')
56         NumberB = float(input('Please input number2:  '))
57         OPFactory = OperationFatory()
58         OPType = OPFactory.ChooseOperation(op)
59         OPType.NumberA = NumberA
60         OPType.NumberB = NumberB
61         print('The result is:', OPType.GetResult())
62         print('\n#--  input q to exit any key to continue')
63         try:
64             ch = input()
65         except:
66             ch = ''

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:100行代码实现“跳一跳”辅助程序

下一篇:python基础_类型_list