abstractoperation.py //抽象操作类
代码如下:
import string
class Operation(object):
def __init__(self):
pass
def init(self, num1, num2):
self.numA = string.atoi(num1)
self.numB = string.atoi(num2)
def Getresult():
pass
operation.py //实现具体操作的类
代码如下:
from abstractoperation import *
class OperationAdd(Operation):
def Getresult(self):
return self.numA + self.numB
class OperationSub(Operation):
def Getresult(self):
return self.numA - self.numB
class OperationMul(Operation):
def Getresult(self):
return self.numA * self.numB
class OperationDiv(Operation):
def Getresult(self):
if self.numB == 0:
return 'error'
return self.numA / self.numB
faction.py //工厂类
代码如下:
from operation import *
class Factory(object):
obj = None
def main(self, str):
if str == '+':
obj = OperationAdd()
elif str == '-':
obj = OperationSub()
elif str == '*':
obj = OperationMul()
elif str == '/':
obj = OperationDiv()
else:
pass
return obj
client.py //用来测试的客户端程序
代码如下:
#!/usr/bin/env python
from factory import *
num1 = raw_input('please input the first num:')
optType = raw_input('please input the operation type:')
num2 = raw_input('please input the second num:')
factory = Factory()
opt = factory.main(optType)
opt.init(num1, num2)
result = opt.Getresult()
print(result)
通过执行客户端程序就可以看到程序运行的结果,这里使用的python版本是2.7.5,对于python3来说,可能有点不同。。。。