鱼C论坛

 找回密码
 立即注册
查看: 3132|回复: 1

把装饰器转换为这个为什么错了?

[复制链接]
发表于 2022-10-15 21:42:21 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 zzhsb 于 2022-10-15 21:46 编辑
  1. def type_check(correct_type):
  2.     def outer(func):
  3.         def inner(arg):
  4.             if(type(arg) == correct_type):
  5.                 return func(arg)
  6.             else:
  7.                 return "参数类型错误!"
  8.         return inner
  9.     return outer
  10.    
  11.    
  12. print("<<<--- 测试整数 --->>>")
  13.    
  14. @type_check(int)
  15. def double(x):
  16.     return x * 2
  17.    
  18. print(double(2))      # 这里打印结果应该是 4
  19. print(double("2"))    # 这里打印结果应该是 “参数类型错误”
  20.    
  21. print("\n<<<--- 测试字符串 --->>>")
  22.    
  23. @type_check(str)
  24. def upper(s):
  25.     return s.upper()
  26.    
  27. print(upper('I love FishC.'))   # 这里打印结果应该是 I LOVE FISHC
  28. print(upper(250))               # 这里打印结果应该是 “参数类型错误”
复制代码


把装饰器转换为原本的样貌是:
  1. def type_check(correct_type):
  2.     def outer(func):
  3.         def inner(arg):
  4.             if (type(arg) == correct_type):
  5.                 return func(arg)
  6.             else:
  7.                 return "参数类型错误!"
  8.         return inner
  9.     return outer

  10. print("<<<--- 测试整数 --->>>")


  11. def double(x):
  12.     return x*2
  13. print(double(2))
  14. print(double('2'))

  15. print("\n<<<--- 测试字符串 --->>>")


  16. def upper(s):
  17.     return s.upper()
  18. print(upper('I love FishC'))
  19. print(upper(250))

  20. double = type_check(int)(double)
  21. upper = type_check(str)(upper)
复制代码


为什么会报错呢?转换错了吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-10-15 21:49:22 | 显示全部楼层
会了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-26 10:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表