代码之家  ›  专栏  ›  技术社区  ›  alekscooper

我们什么时候调用实际上的decorator中的内部函数?

  •  0
  • alekscooper  · 技术社区  · 6 年前

    我正在努力理解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() 所以它可以打印这些线条。

    我们什么时候打电话 包装件() ?

    1 回复  |  直到 6 年前
        1
  •  1
  •   juanpa.arrivillaga    6 年前

    返回 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'