1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| import sys
class OperationFactory(object): ''' factory class to generate operation function ''' def __init__(self, operation): self.operation = operation
def createOperation(self): oper = None if self.operation == '+': oper = OperationAdd() elif self.operation == '-': oper = OperationSub() elif self.operation == '*': oper = OperationMul() elif self.operation == '/': oper = OperationDiv() elif self.operation == '**': oper = OperationPow() else: raise Exception, 'No correct operation.'
return oper
class Operation(object): ''' base class operation ''' def __init__(self): self.numA = 0 self.numB = 0 print 'Init Operation class', self.numA, self.numB
def getResult(self): print 'Call Operation function', self.numA, self.numB result = 0 return result
class OperationAdd(Operation):
def __init__(self): Operation.__init__(self) print 'Init OperationAdd class', self.numA, self.numB
def getResult(self): print 'Call OperationAdd function', self.numA, self.numB result = 0 result = self.numA + self.numB return result class OperationSub(Operation):
def __init__(self): Operation.__init__(self) print 'Init OperationSub class', self.numA, self.numB
def getResult(self): print 'Call OperationSub function', self.numA, self.numB result = 0 result = self.numA - self.numB return result
class OperationMul(Operation):
def __init__(self): Operation.__init__(self) print 'Init OperationMul class', self.numA, self.numB
def getResult(self): print 'Call OperationMul function', self.numA, self.numB result = 0 result = self.numA * self.numB return result
class OperationDiv(Operation):
def __init__(self): Operation.__init__(self) print 'Init OperationDiv class', self.numA, self.numB
def getResult(self): print 'Call OperationDiv function', self.numA, self.numB result = 0 try: result = self.numA / self.numB except ZeroDivisionError, e: raise e return result
class OperationPow(Operation):
def __init__(self): Operation.__init__(self) print 'Init OperationPow class', self.numA, self.numB
def getResult(self): print 'Call OperationPow function', self.numA, self.numB result = 0 result = self.numA ** self.numB return result
def main(): if len(sys.argv) != 4: print 'Please enter two number and one operation like 3 + 2' sys.exit(-1)
numA = int(sys.argv[1]) operation = sys.argv[2] numB = int(sys.argv[3])
oper = OperationFactory(operation).createOperation() oper.numA = numA oper.numB = numB result = oper.getResult() print result
main()
|