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

Python装饰器未执行求助:自定义do_twice装饰器无输出

问题排查与解决

你的装饰器代码本身是正确的,导致无输出的原因很简单:你只定义了被装饰的say_whee()函数,但从未调用它。Python中函数定义后不会自动执行,必须显式调用才会触发执行逻辑。

修改后的main.py代码

from decorator import do_twice


@do_twice
def say_whee():
    print("Whee!")

# 关键:调用函数才能触发执行
say_whee()

运行修改后的代码,就能得到你预期的输出:

Whee!
Whee!

额外补充(可选)

如果后续你的函数需要接收参数,当前的do_twice装饰器会失效,此时可以修改装饰器让它支持任意参数:

def do_twice(func):
    def wrapper_do_twice(*args, **kwargs):
        func(*args, **kwargs)
        func(*args, **kwargs)
    return wrapper_do_twice

这样即使是带参数的函数,比如:

@do_twice
def greet(name):
    print(f"Hello {name}!")

greet("Alice")

也能正常执行两次,输出:

Hello Alice!
Hello Alice!

内容的提问来源于stack exchange,提问作者user20750684

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:02:04