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

Python装饰器疑问:未调用被装饰函数,执行x.py为何产生输出?

为什么未调用被装饰函数却自动执行了?

问题出在你的装饰器返回的是执行后的wrapper函数结果,而不是wrapper函数本身!下面一步步拆解原因和修正方法:

装饰器的工作逻辑

当你用@my_decorator_module装饰just_some_function时,Python会自动帮你执行等价代码:

just_some_function = my_decorator_module(just_some_function)

现在看你写的装饰器代码:

def my_decorator_module(some_function):
    def wrapper():
        num = 10
        if num == 10:
            print('yess')
        else:
            print('no')
        some_function()
        print('print after some_function() called')
    return wrapper()  # 这里是核心错误!你直接调用了wrapper并返回结果

当Python处理装饰器语法时,会立刻调用my_decorator_module(just_some_function)。这个函数内部定义完wrapper后,直接执行了wrapper(),把执行后的返回值(这里wrapper没有显式return,所以是None)赋值给了just_some_function。

这就导致在导入x.py的瞬间,wrapper里的所有代码(包括调用原just_some_function)都自动跑了一遍,根本不需要你手动调用just_some_function()。

修正方法

把装饰器的返回值改成wrapper(不要加括号),返回函数对象本身,而不是执行它:

# abc.py 修正后的代码
def my_decorator_module(some_function):
    def wrapper():
        num = 10
        if num == 10:
            print('yess')
        else:
            print('no')
        some_function()
        print('print after some_function() called')
    return wrapper  # 返回函数对象,而非执行结果

之后在x.py中,只有当你手动调用just_some_function()时,才会触发wrapper的执行:

# x.py
from abc import my_decorator_module
@my_decorator_module
def just_some_function():
    print("Wheee!")

# 现在只有调用该函数才会输出内容
just_some_function()

这样修改后,运行x.py时不调用函数就不会有输出,调用后才会按顺序打印yess、Wheee!、print after some_function() called。

内容的提问来源于stack exchange,提问作者Jaskaran singh Rajal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:26:59