在Python中为函数装饰器创建别名

1 投票
1 回答
2857 浏览
提问于 2025-05-10 20:20

在Python中,函数装饰器也是一种函数,它们可以像普通变量一样被灵活地赋值和传递。下面的例子展示了这一点:

def auth_token_not_expired(function):
    @auth_token_right
    def wrapper(req):
        # Some validations
        return function(req)
    return wrapper

我尝试把这个装饰器函数赋值给另一个变量,作为别名:

login_required = auth_token_not_expired

在检查时发现赋值是成功的,但当我用@login_required的语法调用它时,却出现了NameError错误。

Exception Type: NameError
Exception Value:    
name 'login_required' is not defined

那么,我们该如何把这个login_required变量也注册为装饰器呢?

相关文章:

  • 暂无相关问题
暂无标签

1 个回答

2

你在错误的范围内。

这个例子是改编自 如何制作函数装饰器的链条?

def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

@makeitalic
def hello():
    return "hello world"

hello() ## returns <i>hello world</i>

现在进行作业:

mi = makeitalic

@mi
def helloit():
    return "hello world"

helloit() ## returns <i>hello world</i>

撰写回答