# 面向对象的综合应用 # 计算器:实现一些基本的计算操作,已经打印结果 # --------------- 代码1 ---------------------- def add(x, y): return x + y def subtract(x, y): return x - y def mulit(x, y): return x * y print(add(2, 4)) # 6 # 实现 (2 + 4 - 3) * 5 res1 = add(2, 4) res2 = subtract(res1, 3) res3 = res2 * 5 print(res3) # 15 # --------------- 代码2 ----------------------- class Caculator: __result = 0 @classmethod #设置一个首数 def first_value(cls, value): cls.__result = value @classmethod def add(cls, n): cls.__result += n @classmethod def subtract(cls, n): cls.__result -= n @classmethod def mulit(cls, n): cls.__result *= n @classmethod def show(cls): return cls.__result Caculator.first_value(2) Caculator.add(4) Caculator.subtract(3) Caculator.mulit(5) print(Caculator.show()) # 15 # --------------- 代码3 ----------------------- class Caculator: def __init__(self, firstNum): self.__result = firstNum def add(self, n): self.__result += n def subtract(self, n): self.__result -= n def mulit(self, n): self.__result *= n def show(self): return self.__result c = Caculator(2) c.add(4) c.subtract(3) c.mulit(5) print(c.show()) # 15 # --------------- 代码4 容错处理 ----------------------- class Caculator: def __check_num_zsq(func): def inner(self, n): if not isinstance(n, int): raise TypeError("数据类型错误") return func(self, n) return inner @__check_num_zsq def __init__(self, firstNum): self.__result = firstNum @__check_num_zsq def add(self, n): self.__result += n @__check_num_zsq def subtract(self, n): self.__result -= n @__check_num_zsq def mulit(self, n): self.__result *= n def show(self): return self.__result c = Caculator(2) c.add(4) c.subtract(3) c.mulit(5) print(c.show()) # 15
原文地址:https://www.cnblogs.com/delphiclub/p/8625378.html
时间: 2024-10-10 20:13:30