对口译员在做什么感到好奇

2024-05-03 10:09:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习装饰设计模式教程 (归功于Ryoo Jungwoo)

我很好奇为什么我可以换行:return decoratorprint(hello_world())return decorator()print(hello_world)

from functools import wraps

def make_blink(function):
    """Defines the decorator"""

    @wraps(function)
    # Define the inner function
    def decorator():

        # Grab the return value of the function being decorated
        ret = function()
        # Add new functionality to the function being decorated
        return "<blink>"+ ret + "<b/link>"
    return decorator #return decorator()#<THIS LINE HERE SWAPPED

# Apply the decorator here!
@make_blink
def hello_world():
    """Original function! """

    return "Hello, World!"

# Check the result of decorating
print(hello_world()) #print(hello_world) #<THIS LINE HERE SWAPPED

翻译不是每次都在做不同的事情吗?我只是想了解一些情况,以便更好地了解正在发生的事情


Tags: ofthehelloworldmakereturndeffunction
1条回答
网友
1楼 · 发布于 2024-05-03 10:09:41

装饰器实际上就是函数,函数就是对象。你知道吗

台词

@make_blink
def hello_world():
    # ...

基本上与

def hello_world():
    # ...
hello_world = make_blink(hello_world)

但是函数对象从来没有首先分配给hello_world(它在堆栈上,以便传递给装饰器)。你知道吗

所以无论你从make_blink()返回什么,都会被分配回hello_world。它可以是函数对象,但也可以是完全不同的对象。你知道吗

因此,当您使用return decorator时,您告诉Python将hello_world设置为嵌套函数对象。当您使用return decorator()时,您告诉Python使用decorator()函数的结果。这里,这是一个字符串值。就好像你这么做了:

def hello_world():
    """Original function! """
    return "Hello, World!"

hello_world = "<blink>" + hello_world() + "</blink>"

对于这个特定的例子来说,这很好,因为hello_world()函数体每次只返回相同的字符串。你知道吗

但是,如果您更改了原始的hello_world()函数体,每次调用时都返回不同的内容,会怎么样?如果你有:

import random

@make_blink
def random_greeting():
    return 'Hello ' + random.choice('DonAr', 'Martijn Pieters', 'Guido van Rossum') + '!'

现在,从make_blink()调用返回的结果有很大的不同!对于模块的顶层,在导入时,装饰器只执行一次。如果您使用return decorator(),那么只需运行random.choice()一次,就可以将random_greeting的值固定到一个静态字符串结果中。你知道吗

一般来说,装饰程序需要再次返回一个可调用对象。可以是原始函数(decorator只是更新某种注册)、包装函数(在调用原始函数之前或之后执行额外的操作),甚至是完全不同的东西。但这不是一成不变的,翻译也不在乎。你知道吗

decorator只是可重用的东西,可以在程序中使用,这是一种工具。如果您对返回原始函数结果的装饰器有特定的用途,那么您可以自由地这样做。你知道吗

相关问题 更多 >