将装饰器应用于导入的功能? [英] Applying a decorator to an imported function?

查看:110
本文介绍了将装饰器应用于导入的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想导入一个函数:

from random import randint

然后应用一个装饰器:

and then apply a decorator to it:

@decorator
randint

我在想这是否有一些语法糖(比如我或者我必须这样做:

I was wondering if there was some syntactic sugar for this (like what I have above), or do I have to do it as follows:

@decorator
def randintWrapper(*args):
    return random.randint(*args)


推荐答案

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

Decorators are just syntactic sugar to replace a function object with a decorated version, where decorating is just calling (passing in the original function object). In other words, the syntax:

@decorator_expression
def function_name():
    # function body

转换为:

translates to:

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

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

In your case, you can apply your decorator manually instead:

from random import randint

randint = decorator(randint)

这篇关于将装饰器应用于导入的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆