如何将装饰器应用于导入的函数? [重复]

问题描述 投票:0回答:1

假设我导入了一个函数:

from random import randint

然后想对其应用装饰器。有没有一些语法糖,也许像这样?

@decorator
randint

或者我是否创建了一个包装函数来装饰,就像这样?

@decorator
def randintWrapper(*args):
    return random.randint(*args)
python function decorator python-decorators
1个回答
68
投票

装饰器只是用装饰版本替换函数对象的语法糖,其中 decorating 只是 calling (传入原始函数对象)。换句话说,语法:

@decorator_expression
def function_name():
    # function body

大致(*) 翻译为:

def function_name():
    # function body
function_name = decorator_expression(function_name)

在您的情况下,您可以手动应用装饰器:

from random import randint

randint = decorator(randint)

(*) 在函数或类上使用

@<decorator>
时,首先不会绑定
def
class
定义的结果(分配给它们在当前命名空间中的名称)。装饰器直接从堆栈传递对象,然后仅绑定装饰器调用的结果。

© www.soinside.com 2019 - 2024. All rights reserved.