【发布时间】:2020-06-17 09:26:43
【问题描述】:
@authenticated 装饰器允许函数在 user1 的“有效”设置为 True 时运行:
user1 = {
'name': 'Sorna',
'valid': False #changing this will either run or not run the message_friends function.
}
def authenticated(fn):
def wrapper(*args , **kwargs):
if args[0]['valid']:
fn(*args, **kwargs)
else:
print(f'You are not authenticated to send messages. Please make deposit of $5 to your account')
return wrapper
@authenticated
def message_friends(user):
print('message has been sent')
message_friends(user1)
我很难理解为什么使用args[0]['valid']。当我使用args[1]['valid] 时出现错误,
我知道我错过了一些关键概念。请帮帮我
【问题讨论】:
-
*args是由您的函数调用提供的,在这种情况下它只有user1,没有args[1] -
是的,user1 是 args[0](函数的第一个唯一参数)
-
args= (位置)参数列表,args[0]= 第一个参数...
标签: python dictionary decorator