为什么装饰器不使用内置函数?

2024-04-26 15:14:38 发布

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

我正在学习如何在Python中使用decorators,我对它有很好的理解,但是我有一个问题-为什么我不能对内置函数使用decorators?你知道吗

为什么这样做:

def decorator1(func):
    def inner(*args, **kwargs):
        print("<>=========================<>")
        func(*args, **kwargs)
        print("<>=========================<>")
    return inner

@decorator1
def greet():
    print("Hello!")


greet()

而不是这个?地址:

def decorator1(func):
    def inner(*args, **kwargs):
        print("<>=========================<>")
        func(*args, **kwargs)
        print("<>=========================<>")
    return inner

@decorator1
print("Hello!")

是不是因为print函数是当场执行的,而greet()函数只是定义的,并且只在@decorator1之后运行?你知道吗


Tags: 函数decoratorshelloreturn定义地址defargs
1条回答
网友
1楼 · 发布于 2024-04-26 15:14:38

@decorator的语法只能与^{} function definition^{} class definition语句一起使用。这并不意味着你不能“装饰”内置功能。你知道吗

但是,您尝试将语法应用于expression statement,即calls函数。最多您会修饰返回值(对于print()函数,返回值总是None)。你知道吗

然而,装饰器只是syntactic sugar。语法

@decorator_expression
def functionname(...): ...

被执行为

def functionname(...): ...

functionname = decorator_expression(functionname)

但是没有functionname被分配两次。你知道吗

所以要修饰print,请显式调用修饰器:

decorated_print = decorator1(print)
decorated_print("Hello!")

注意:我在这里显式地选择了一个不同的名称来分配decorator函数的结果。如果你真的想,你也可以使用print = decorator1(print)。但是您可能希望稍后运行del print来取消内置函数的掩码,或者使用^{}再次访问原始函数。你知道吗

演示:

>>> def decorator1(func):
...     def inner(*args, **kwargs):
...         print("<>=========================<>")
...         func(*args, **kwargs)
...         print("<>=========================<>")
...     return inner
...
>>> decorated_print = decorator1(print)
>>> decorated_print("Hello!")
<>=========================<>
Hello!
<>=========================<>

相关问题 更多 >