简单工厂模式
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 = ''