Recently saw the next big talk design mode, decided to use Python to try to achieve the next.
Basic class
1 class operationbase (): 2 """ 3 base Operations class 4 """ 5 result = 06 def GetResult (self):7 return Self.result
Inheriting classes
1 classOperationadd (operationbase):2 """3 addition class, inheriting base operation class4 """5 def __init__(self,numa,numb):6Self.result = NumA +NumB7 defGetResult (self):8 returnSelf.result9 Ten classoperationsub (operationbase): One """ A subtraction Operation class, inheriting base operation class - """ - def __init__(self,numa,numb): theSelf.result = NumA-NumB - defGetResult (self): - returnSelf.result - + classOperationmult (operationbase): - """ + multiplication class, inheriting base operation class A """ at def __init__(self,numa,numb): -Self.result = NumA *NumB - defGetResult (self): - returnSelf.result - - classOperationdiv (operationbase): in """ - Division Operation class, inheriting the base Operation class, by the divisor of 0 exception capture control dividend cannot be 0 to """ + def __init__(self,numa,numb): - Try: theSelf.result = NumA/NumB * exceptZerodivisionerror: $ Print "the divisor cannot be 0!!! "Panax Notoginseng - defGetResult (self): the returnSelf.result + A#工厂类 the classoperationfactor (): + @staticmethod - defcreateoperate (operate,numa,numb): $ forCaseinchswitch (operate): $ ifCase'+'): -Oper =Operationadd (numa,numb) - Break the ifCase'-'): -Oper =operationsub (numa,numb)Wuyi Break the ifCase'*'): -Oper =Operationmult (numa,numb) Wu Break - ifCase'/'): AboutOper =Operationdiv (numa,numb) $ Break - returnOper - - if __name__=='__main__': Aopt = Raw_input ("Please enter an operator (+-*/):") + Try: theNumA = Float (raw_input ("Please enter a number for the first operation:")) -NumB = Float (raw_input ("Please enter a number for the second operation:")) $ exceptValueError: the Print "Enter the wrong number, please re-enter! " theNumA = Float (raw_input ("Please enter a number for the first operation:")) theNumB = Float (raw_input ("Please enter a number for the second operation:")) the -Oper =operationfactor.createoperate (Opt,float (NumA), float (NumB)) in Print "Result =", Oper. GetResult ()
The case can refer to my other blog
Http://www.cnblogs.com/ListenWind/p/4267517.html
Python's Simple engineering model implementation