【问题标题】:TypeError: 'NoneType' object is not callable in decorators [closed]TypeError:'NoneType'对象在装饰器中不可调用[关闭]
【发布时间】:2020-09-22 12:19:20
【问题描述】:
#decorators in python
users={"ravneet":"elitebook","singh":"punjab"}

def login_required(func):
    def wrapper(username, password, *args, **kwargs):
        if username in users and users[username]==password:
            func(*args,**kwargs)
        else:
            print("not authenticated")
        return wrapper

@login_required
def add(a,b):
    print("a+b: ",a+b)

add("ravneet","elitebook",2,3)

【问题讨论】:

  • 缩进问题,login_required 不返回任何内容。一旦你解决了这个问题,包装器就不会了。

标签: python python-decorators


【解决方案1】:

您的return wrapper 有一个额外的缩进,这使得login_required() 返回None。固定在下面(和repl.it link):

def login_required(func):

    def wrapper(username, password, *args, **kwargs):

        if username in users and users[username]==password:

            func(*args,**kwargs)
        else:

            print("not authenticated")
    return wrapper

@login_required    
def add(a,b):    
    print("a+b: ",a+b)

add("ravneet","elitebook",2,3)

【讨论】:

    猜你喜欢
    • 2020-08-19
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    相关资源
    最近更新 更多