Python之簡單工程模式實現

來源:互聯網
上載者:User

標籤:

最近又看了下大話設計模式,決定用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之簡單工程模式實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.