首页 > 解决方案 > 为什么 python 装饰器的结果是这样的..?

问题描述

这些天,我研究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.

有人能告诉我为什么会这样吗?

标签: pythonpython-decorators

解决方案


当您应用这样的装饰器时:

@my_decorator
def say_hello():

它实际上在幕后做的是:

say_hello = my_decorator(say_hello)

所以如果你这样做:

ret = my_decorator(say_hello)

您实际上调用了两次装饰器,因此您看到的双重消息。


推荐阅读