zoukankan      html  css  js  c++  java
  • 一个面向对象的简单计算器(python)

    #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
    

      

  • 相关阅读:
    Ubuntu 更换软件源
    Ubuntu 配置 SOCKS5
    Ubuntu 配置 Sha-dow-socks
    frp(内网穿透)
    solr 远程代码执行(CVE-2019-12409)
    多线程处理爬虫
    python实现文件自动排序
    python 实现根据文件名自动分类移动至不同的文件夹
    Centos7如何开启任意端口服务
    centos7默认安装没有连接网络
  • 原文地址:https://www.cnblogs.com/bjdxy/p/2835400.html
Copyright © 2011-2022 走看看