You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义logging_decorator装饰器为何输出返回值为0?

问题原因及解决方法

原因分析

你写的装饰器里,wrapper_function调用原函数时没传递接收到的参数:

print(f"It returned:{function()}")

这里执行function()相当于无参数调用my_func,此时my_func的*args是空元组,sum()处理空可迭代对象默认返回0,所以输出的返回值是0。另外,当前的wrapper_function也没有返回原函数的结果,导致return_total最终是None。

修正后的代码

def logging_decorator(function):
    def wrapper_function(*args, **kwargs):
        print(f"You called {function.__name__}{args}")
        result = function(*args, **kwargs)  # 传递接收到的参数给原函数
        print(f"It returned:{result}")
        return result  # 把原函数的返回值传递出去

    return wrapper_function


@logging_decorator
def my_func(*args):
   return sum(args)

return_total = my_func(1,2,3)

运行结果

You called my_func(1, 2, 3)
It returned:6

此时return_total的值也会是6,符合预期。

内容的提问来源于stack exchange,提问作者Joaquín Ruiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:27:09