鱼C论坛

 找回密码
 立即注册
查看: 52|回复: 2

函数第六章节显示return的BUG

[复制链接]
发表于 3 天前 | 显示全部楼层 |阅读模式

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

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

x
import time
def time_master(func):
    print("开始运行程序")
    start=time.time()
    func()
    stop=time.time()
    print("结束程序运行")
    print(f"一共耗费{(stop-start):2f}秒。")
    return call_func

@time_master
def Myfunc():
    time.sleep(2)
    print("hello")

Myfunc()   


运行结果:
==
开始运行程序
hello
结束程序运行
一共耗费2.020955秒。
Traceback (most recent call last):
  File "C:/python学习/time_master.py", line 11, in <module>
    @time_master
  File "C:/python学习/time_master.py", line 9, in time_master
    return call_func
NameError: name 'call_func' is not defined
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 3 天前 | 显示全部楼层
[quote]问题分析:
装饰器代码中存在两个主要问题:
1. return call_func 中的call_func未定义
2. 装饰器没有正确返回包装函数,导致原函数被覆盖

正确代码如下:
  1. python
  2. import time

  3. def time_master(func):
  4.     def wrapper():
  5.         print("开始运行程序")
  6.         start = time.time()
  7.         result = func()  # 执行被装饰的函数
  8.         stop = time.time()
  9.         print("结束程序运行")
  10.         print(f"一共耗费{(stop-start):.2f}秒。")
  11.         return result  # 返回原函数的执行结果
  12.     return wrapper  # 这里返回包装器函数

  13. @time_master
  14. def Myfunc():
  15.     time.sleep(2)
  16.     print("hello")
  17.     return 666  # 测试返回值是否正常

  18. print(Myfunc())  # 测试装饰后的函数
复制代码


修改要点说明:
  • 1. 添加了wrapper()包装函数,这是装饰器的标准结构
  • 2. 通过return wrapper返回真正的包装函数
  • 3. 在wrapper中return func()的执行结果,保留原函数返回值
  • 4. 修正了时间格式化字符串中的冒号位置(:.2f)


运行后正确输出:
开始运行程序
hello
结束程序运行
一共耗费2.00秒。
666

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 3 天前 | 显示全部楼层
FishC 发表于 2025-4-18 10:30
[quote]问题分析:
装饰器代码中存在两个主要问题:
1. return call_func 中的call_func未定义

为什么要加包装器函数
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-21 14:49

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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