#coding=utf8 import string def count(numA, numB, operator): try: numberA = string.atof(numA) numberB = string.atof(numB) except: exit("input error,please check it number A :'%s' -- number B:'%s'" % (numA, numB)) op = OperationFactory.createOperate(operator) op.setA(numberA) op.setB(numberB) return op.getResult() class OperationFactory(object): ''' 工厂方法,生成对应操作类 ''' @staticmethod def createOperate(operate): operators = { '+':OperationAdd(), '-':OperationSub(), '*':OperationMul(), '/':OperationDiv(), } try: return operators[operate] except KeyError: exit("Temporarily does not support '%s' operator" % operate) class Operation(object): ''' 操作父类,在需要时可以增加相应子类,如取模类OperationMod,复数类等,增加子类不影响其他子类的运算, 达到封装的目的 ''' _numberA = 0 _numberB = 0 def NumberA(self): return self._numberA def NumberB(self): return self._numberB def getResult(self): return 0 def setA(self, A): self._numberA = A def setB(self, B): self._numberB = B class OperationAdd(Operation): def getResult(self): result = self.NumberA() + self.NumberB() return result class OperationSub(Operation): def getResult(self): result = self.NumberA() - self.NumberB() return result class OperationMul(Operation): def getResult(self): result = self.NumberA() * self.NumberB() return result class OperationDiv(Operation): def getResult(self): result = self.NumberA() / self.NumberB() return result if __name__ == '__main__': left = raw_input('number A: ') sign = raw_input('请输入 + - * / :') right = raw_input('number B: ') rs = count(left, right, sign) print rs