|
本帖最后由 jackz007 于 2025-5-13 21:59 编辑
- @type_check(int)
- def double(x):
复制代码
用户函数 double() 被 type_check(int) 装饰,当这样调用函数 double() 时:
Python 将实际执行这一句:
- k = type_check(int)(double)(x)
复制代码
- @type_check(str)
- def upper(s):
复制代码
用户函数 upper() 被 type_check(str) 装饰,当这样调用函数 upper() 时:
Python 将实际执行这一句:
- k = type_check(str)(upper)(s)
复制代码
本例不使用装饰器的完整代码如下:
- 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
-
- # @type_check(int) # 必须先注释掉装饰器定义
- def double(x):
- return x * 2
- # @type_check(str) # 必须先注释掉装饰器定义
- def upper(s):
- return s . upper()
- # 下面的代码模拟装饰器机制
- print("<<<--- 测试整数 --->>>")
- print(type_check(int)(double)(2)) # print(double(2)) # 这里打印结果应该是 4
- print(type_check(int)(double)("2")) # print(double("2")) # 这里打印结果应该是 “参数类型错误”
- print("\n<<<--- 测试字符串 --->>>")
- print(type_check(str)(upper)('I love FishC.')) # print(upper('I love FishC.')) # 这里打印结果应该是 I LOVE FISHC
- print(type_check(str)(upper)(250)) # print(upper(250)) # 这里打印结果应该是 “参数类型错误”
复制代码 |
|