标签:print bsp obj ret abc divide 简单工厂 sop 代码实现
定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
用任意一种面向对象语言实现一个计算器控制台程序。要求输入两个数和运算符号,得到结果。
#!/usr/bin/env python # _*_ coding utf-8 _*_ #Author: aaron import abc class Operation(object): def __init__(self, NumberA=0, NumberB=0): self.NumberA = NumberA self.NumberB = NumberB def GetResult(self): pass class AddOp(Operation): def GetResult(self): return self.NumberB + self.NumberA class MinusOp(Operation): def GetResult(self): return self.NumberA - self.NumberB class MultiOp(Operation): def GetResult(self): return self.NumberA * self.NumberB class DivideOp(Operation): def GetResult(self): try: return 1.0 * self.NumberA / self.NumberB except ZeroDivisionError: raise class Factory(metaclass=abc.ABCMeta): @abc.abstractmethod def create_factory(self): ‘‘‘工厂类抽象接口‘‘‘ class AddFactory(Factory): def create_factory(self): return AddOp() class MinusFactory(Factory): def create_factory(self): return MinusOp() class MultiFactory(Factory): def create_factory(self): return MultiOp() class DivideFactory(Factory): def create_factory(self): return DivideOp() if __name__ == ‘__main__‘: ch = ‘‘ while not ch == ‘q‘: NumberA = eval(input(‘Please input number1: ‘)) op = str(input(‘Please input the operation: ‘)) NumberB = eval(input(‘Please input number2: ‘)) if op == ‘+‘: OPFactory = AddFactory() elif op == ‘-‘: OPFactory = MinusFactory() elif op == ‘*‘: OPFactory = MultiFactory() elif op == ‘/‘: OPFactory = DivideFactory() else: print(‘invilid input!‘) oper = OPFactory.create_factory() oper.NumberA = NumberA oper.NumberB = NumberB print(‘The result is:‘, oper.GetResult()) print(‘\n#-- input q to exit any key to continue‘) try: ch = str(input()) except: ch = ‘‘
标签:print bsp obj ret abc divide 简单工厂 sop 代码实现
原文地址:https://www.cnblogs.com/cjaaron/p/9075890.html