python:多个装饰器的执行顺序

36 篇文章 1 订阅

我们通过下面这个例子来看多个为装饰器的执行顺序。

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')
运行结果:
判断用户
判断登录
登录成功
用户正确
添加学生信息...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值