乙個物件導向的簡單計算器 python

2022-03-09 10:53:58 字數 1914 閱讀 2788

#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 =

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('請輸入 + - * / :')

物件導向編寫乙個計算器

首先分析計算器有加減乘除,取模,求餘等計算方式,所以我們在建立了這個類的同時就應該想到後期肯定需要進行這方面的擴充套件,所以在設計的時候就應該盡量不修改原有 的前提下進行功能的擴充套件,也就是降低物件之間的耦合度。廢話不多說,如下 namespace program public print dec...

乙個簡單的計算器

乙個非常簡單的計算器 來自sololearn 只能進行單一計算 while true print 設定 print enter 增加 to 增加 two numbers print enter 減去 to 減去 two numbers print enter 相乘 to 相乘 two numbers...

製作乙個簡單的計算器

coding utf 8 time 2020 2 5 author wowilliam210 file calculator.py software pycharm import win32com.client class acalculator object def check num zsq f...