我正在尝试在pycharm中执行以下代码。
def auth_login(func):
def wrapper(*args, **kwargs):
print("Authenticating......")
func(*args, **kwargs)
return wrapper()
@auth_login
def login(username, password):
print("Successfully logged in:",username)
login('setu', 'setu')
看起来很直接,但我收到以下错误: 输出:
> Traceback (most recent call last):
> Authenticating......
> File "C:/Users/611834094/PycharmProjects/PractiseProject/decorators/example3.py",
> line 10, in <module>
> @auth_login
> File "C:/Users/611834094/PycharmProjects/PractiseProject/decorators/example3.py",
> line 7, in auth_login
> return wrapper()
> File "C:/Users/611834094/PycharmProjects/PractiseProject/decorators/example3.py",
> line 5, in wrapper
> func(*args, **kwargs)
> TypeError: login() missing 2 required positional arguments: 'username' and 'password'
>
> Process finished with exit code 1
答案 0 :(得分:3)
您正在返回包装器的值。而只是返回功能。
def auth_login(func):
def wrapper(*args, **kwargs):
print("Authenticating......")
func(*args, **kwargs)
return wrapper # Here was the issue.
@auth_login
def login(username, password):
print("Successfully logged in:",username)
login('setu', 'setu')
答案 1 :(得分:1)
在返回包装函数时删除括号
def auth_login(func):
def wrapper(*args, **kwargs):
print("Authenticating......")
func(*args, **kwargs)
# Remove the brackets from wrapper
return wrapper