標籤:
最近又看了下大話設計模式,決定用Python來試著實現下。
基礎類
1 class OperationBase():2 """3 基礎運算類4 """5 result = 06 def GetResult(self):7 return self.result
繼承類
1 class OperationAdd(OperationBase): 2 """ 3 加法類,繼承基礎運算類 4 """ 5 def __init__(self,numA,numB): 6 self.result = numA + numB 7 def GetResult(self): 8 return self.result 9 10 class OperationSub(OperationBase):11 """12 減法運算類,繼承基礎運算類13 """14 def __init__(self,numA,numB):15 self.result = numA - numB16 def GetResult(self):17 return self.result18 19 class OperationMult(OperationBase):20 """21 乘法運算類,繼承基礎運算類22 """23 def __init__(self,numA,numB):24 self.result = numA * numB25 def GetResult(self):26 return self.result27 28 class OperationDiv(OperationBase):29 """30 除法運算類,繼承基礎運算類,通過被除數為0異常捕獲控制被除數不能為031 """32 def __init__(self,numA,numB):33 try:34 self.result = numA / numB35 except ZeroDivisionError:36 print "除數不能為0!!!"37 38 def GetResult(self):39 return self.result40 41 #工廠類42 class OperationFactor():43 @staticmethod44 def createOperate(operate,numA,numB):45 for case in switch(operate):46 if case(‘+‘):47 oper = OperationAdd(numA,numB)48 break49 if case(‘-‘):50 oper = OperationSub(numA,numB)51 break52 if case(‘*‘):53 oper = OperationMult(numA,numB)54 break55 if case(‘/‘):56 oper = OperationDiv(numA,numB)57 break58 return oper59 60 if __name__ == ‘__main__‘:61 opt = raw_input("請輸入一個運算操作符(+-*/):")62 try:63 numA = float(raw_input("請輸入第一個運算的數字:"))64 numB = float(raw_input("請輸入第二個運算的數字:"))65 except ValueError:66 print "輸入數字不對,請重新輸入!"67 numA = float(raw_input("請輸入第一個運算的數字:"))68 numB = float(raw_input("請輸入第二個運算的數字:"))69 70 oper = OperationFactor.createOperate(opt,float(numA),float(numB))71 print "Result = ",oper.GetResult()
裡面的case可以參考我另外一篇部落格
http://www.cnblogs.com/ListenWind/p/4267517.html
Python之簡單工程模式實現