Skip to main content
 首页 » 编程设计

python之装饰函数返回 "None"

2025年05月04日15pengyingh

我是 python 的新手,我刚刚遇到装饰器。我仍然对他们有点困惑,但我正在学习

我试图制作一个装饰器来告诉我我的函数完成了多少时间,但显然当我尝试在应该返回某些东西的函数上使用它时,它只返回“无”

我只看到几个关于这个问题的问题,但没有一个真正有帮助

这是我的代码

import time 
 
 
def time_it(func):  # Here i make a simple decorator function that should time my decorated function 
    def wrapper(*args, **kwargs): 
        t1 = time.time() 
        func(*args) 
        t2 = time.time() 
        total = t2 - t1 
        print("The function '" + func.__name__ + "' took", str(total)[0:5], "seconds to complete") 
 
    return wrapper 
 
 
@time_it 
def square(nums):  # I make a function that squares every number in a list 
    new_list = [] 
    for n in nums: 
        new_list.append(n ** 2) 
    return new_list 
 
 
lis = [f for f in range(200000)]  # i make a list with a range of 200000 
print(square(lis))   

抱歉任何语法错误,我不是英语母语者

请您参考如下方法:

问题是您的内部函数返回值没有被返回。更改记录如下:

from functools import wraps 
 
def time_it(func):  # Here i make a simple decorator function that should time my decorated function 
    @wraps(func) 
    def wrapper(*args, **kwargs): 
        t1 = time.time() 
        ## Note the change on this line -- I now store the return result from the called function  
        result = func(*args, **kwargs) 
        t2 = time.time() 
        total = t2 - t1 
        print("The function '" + func.__name__ + "' took", str(total)[0:5], "seconds to complete") 
 
        ## And then explicitly return the result 
        return result 
 
    return wrapper 

对于装饰器,您需要记住它只是一个闭包,带有一些花哨的语法。您仍然需要自己处理函数返回参数。

一些补充: