我们通过下面这个例子来看多个为装饰器的执行顺序。
def decorator_a(func):
print('Get in decorator_a')
def inner_a(*args,**kwargs):
print('Get in inner_a')
res = func(*args,**kwargs)
return res
return inner_a
def decorator_b(func):
print('Get in decorator_b')
def inner_b(*args,**kwargs):
print('Get in inner_b')
res = func(*args,**kwargs)
return res
return inner_b
@decorator_b
@decorator_a
def f(x):
print('Get in f')
return x * 2
f(1)
运行结果:
Get in decorator_a
Get in decorator_b
Get in inner_b
Get in inner_a
Get in f
练习题:判断用户是不是root用户,root用户可添加删除,查看多个装饰器的执行顺序
def pd1(fun1):
print('判断登录')
def wrapper1(name, passwd):
if name == 'root' and passwd == '123':
print('登录成功')
res1=fun1(name, passwd)
return res1
else:
print('密码错误')
return wrapper1
def pd2(fun2):
print('判断用户')
def wrapper2(name, passwd):
if name == 'root':
print('用户正确')
res2 = fun2(name, passwd)
return res2
else:
print('不是root用户')
return wrapper2
@pd1
@pd2
def add_student(name, passwd):
print('添加学生信息...')
add_student('root', '123')
运行结果:
判断用户
判断登录
登录成功
用户正确
添加学生信息...