kyp*_*hos 28 python function decorator python-decorators
我想导入一个函数:
from random import randint
Run Code Online (Sandbox Code Playgroud)
然后应用装饰器:
@decorator
randint
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一些语法糖(就像我上面所说的那样),或者我必须这样做:
@decorator
def randintWrapper(*args):
return random.randint(*args)
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 39
装饰器只是用于用装饰版本替换函数对象的语法糖,其中装饰只是调用(传入原始函数对象).换句话说,语法:
@decorator_expression
def function_name():
# function body
Run Code Online (Sandbox Code Playgroud)
粗略地(*)转换为:
def function_name():
# function body
function_name = decorator_expression(function_name)
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您可以手动应用装饰器:
from random import randint
randint = decorator(randint)
Run Code Online (Sandbox Code Playgroud)
(*)在@<decorator>函数或类上使用时,def或者class定义的结果不是第一个绑定(在当前命名空间中分配给它们的名称).装饰器直接从堆栈传递对象,然后只绑定装饰器调用的结果.