简单工厂
# 抽象类 class Operation(): def __init__(self, NumberA=0, NumberB=0): self.NumberA = NumberA self.NumberB = NumberB def get_result(self): pass # 具体类 class AddOp(Operation): def get_result(self): return self.NumberB + self.NumberA class MinusOp(Operation): def get_result(self): return self.NumberA - self.NumberB class MultiOp(Operation): def get_result(self): return self.NumberA * self.NumberB class DivideOp(Operation): def get_result(self): try: return self.NumberA / self.NumberB except ZeroDivisionError: raise # 简单工厂 class OperationFatory(): def ChooseOperation(self, op): if op == '+': return AddOp() if op == '-': return MinusOp() if op == '*': return MultiOp() if op == '/': return DivideOp() if __name__ == '__main__': factory = OperationFatory() f = factory.ChooseOperation('/') f.NumberA = 3 f.NumberB = 5 print(f.get_result()) 简单工厂