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
相关产品推荐
相关产品推荐

