首页 > 解决方案 > 我们什么时候调用 de-facto 装饰器中的内部函数?

问题描述

我正在努力理解 Python 中的比较器,其中一个教程建议查看以下示例:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

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

say_whee = my_decorator(say_whee)

say_whee()

当我调用say_whee()它时,它会打印以下内容:

Something is happening before the function is called.
Whee!
Something is happening after the function is called.

我隐约明白为什么它会打印这些行,但我不明白我们什么时候打电话wrapper()所以它可以打印这些行。

我们什么时候打电话wrapper()

标签: pythondecorator

解决方案


返回wrapper并将其分配给say_wee

say_whee = my_decorator(say_whee)

所以在这里调用它:

say_whee()

你自己看:

>>> def my_decorator(func):
...     def wrapper():
...         print("Something is happening before the function is called.")
...         func()
...         print("Something is happening after the function is called.")
...     return wrapper
...
>>> def say_whee():
...     print("Whee!")
...
>>> say_whee = my_decorator(say_whee)
>>>
>>> say_whee
<function my_decorator.<locals>.wrapper at 0x1040d89d8>
>>> say_whee.__name__
'wrapper'

推荐阅读