问题分析:
装饰器的本质是函数嵌套调用。当使用 @decorator 语法糖时,实际上是在将被装饰函数作为参数传递给装饰器。拆开写可以帮助理解执行流程。
拆解步骤:
- 原装饰器写法:
- @type_check(int)
- def double(x):
- return x * 2
复制代码
- 等价的手动装饰写法:
- def double(x): # 原始函数定义
- return x * 2
- # 手动装饰过程
- double = type_check(int)(double) # 分两步执行:
- # 1. type_check(int) 返回 outer 函数
- # 2. outer(double) 返回 inner 函数
复制代码
完整拆解验证代码:
- # 定义装饰器工厂
- def type_check(correct_type):
- def outer(func):
- def inner(arg):
- if type(arg) == correct_type:
- return func(arg)
- else:
- return "参数类型错误!"
- return inner
- return outer
- # 原始函数定义
- def _double(x):
- return x * 2
- def _upper(s):
- return s.upper()
- # 手动应用装饰器
- double = type_check(int)(_double) # 先传参int,再传函数_double
- upper = type_check(str)(_upper) # 先传参str,再传函数_upper
- # 测试验证
- print(double(2)) # 输出 4
- print(double("2")) # 输出 "参数类型错误!"
- print(upper('FishC')) # 输出 "FISHC"
- print(upper(250)) # 输出 "参数类型错误!"
复制代码
关键理解点:
- 装饰器工厂 type_check(int) 先执行,返回 outer 函数
- 外层闭包保存了类型参数 correct_type=int/str
- 最终被调用的是 inner 函数,它包裹了原始函数
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。