【发布时间】:2019-03-24 22:32:20
【问题描述】:
这几天在研究python装饰器,我的问题代码是这样的。
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("hello!")
ret = my_decorator(say_hello)
ret()
其实,我期待这个结果
Something is happening before the function is called.
hello!
Something is happening after the function is called.
但真正的输出是这样的。
Something is happening before the function is called.
Something is happening before the function is called.
hello!
Something is happening after the function is called.
Something is happening after the function is called.
谁能告诉我为什么会出现这样的结果?
【问题讨论】:
-
因为你使用了 2 次装饰器,第一次使用
@my_decorator,第二次使用:my_decorator(say_hello) -
这个问题应该作为一个错字关闭,它对 OP 的其他人没有帮助,尤其是这种点击诱饵标题