Loading... ## 待补充 > 通过实现一个带语音播报的计算器来 更进一步说明 链式调用 与 类中带参数的装饰器的实现 ``` # author: Michael # email: yangowen@126.com class Calculator: # 此处的装饰器只是给内部方法使用的, 外部使用会报错, 所以定义为私有实例方法 def __check_wrapper(func): def inner(self, n): if not isinstance(n, int): raise TypeError('必须是int类型') res = func(self, n) return res return inner # 因为要针对不同运算类型动态生成装饰器, 所以需要使用带参数的装饰器 def __log_warpper(do): def __warpper(func): def inner(self, n): # 利用print来模拟实时数字播报 print(f'{do} {n}') res = func(self, n) return res return inner return __warpper @__check_wrapper @__log_warpper("") def __init__(self, init_num): self.result = init_num @__check_wrapper @__log_warpper("+") def jia(self, n): self.result += n # 通过返回对象本身, 来实现链式调用 return self @__check_wrapper @__log_warpper("-") def jian(self, n): self.result -= n return self @__check_wrapper @__log_warpper("×") def cheng(self, n): self.result *= n return self @__check_wrapper @__log_warpper("÷") def chu(self, n): self.result /= n return self def show(self): print(self.result) return self c = Calculator(0) c.jia(1).jian("a").cheng(5).chu(2).show() ``` © 允许规范转载