夏瑾 发表于 2025-4-18 10:29:23

函数第六章节显示return的BUG

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

FishC 发表于 2025-4-18 10:30:08

问题分析:
装饰器代码中存在两个主要问题:
1. return call_func 中的call_func未定义
2. 装饰器没有正确返回包装函数,导致原函数被覆盖

正确代码如下:
python
import time

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

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

print(Myfunc())# 测试装饰后的函数


修改要点说明:

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


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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

夏瑾 发表于 2025-4-18 10:41:04

FishC 发表于 2025-4-18 10:30
问题分析:
装饰器代码中存在两个主要问题:
1. return call_func 中的call_func未定义


为什么要加包装器函数

player-none 发表于 2025-5-26 18:37:07

夏瑾 发表于 2025-4-18 10:41
为什么要加包装器函数

你这种问题就很没有意义

一定能行 发表于 前天 16:46

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

def myfunc():
    time.sleep(2)
    print("hello")

time_master(myfunc)

不加装饰器的样子
页: [1]
查看完整版本: 函数第六章节显示return的BUG