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

版权声明:©2004 Microsoft Corporation. All rights reserved. https://blog.csdn.net/qq_42036824/article/details/86592725

多个装饰器的执行顺序:

  • 以下我们用一个例子查看多个装饰器的执行顺序
def decorator_a(func):
    print('Get in decorator_a')
    def inner_a(*args,**kwargs):
        print('Get in inner_b')
        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

print(f(1))

结果:
Get in decorator_a
Get in decorator_b
Get in inner_b
Get in inner_b
Get in f
2
  • 例题:
    定义装饰器log,用户判断用户是否登陆成功
    定义装饰器isroot,用于判断用户是不是为root
    编写这2个装饰器:先判断是否登陆成功,再判断是不是root用户
import functools
import inspect


def is_root(fun):
    @functools.wraps(fun)
    def wrapper(*args,**kwargs):
        #inspect.getcallargs返回值是字典,key值为:形参,value值为:形参对应实参
        inspect_res = inspect.getcallargs(fun,*args,**kwargs)
        print('inspect_res的返回值为:%s' %inspect_res)
        if inspect_res.get('name') == 'root':
            print('is root')
            res = fun(*args,**kwargs)
            return res
        else:
            print('not root user')
    return wrapper

li = ['root','westos','redhat']

def log(fun):
    @functools.wraps(fun)
    def inlog(name):
        if name in li:
            print('登陆成功')
            res = fun(name)
            return res
        else:
            print('登陆失败')
    return inlog


@log
@is_root

def add_student(name):   ##此处的name为inspect.getcallargs返回字典中的key值
    print('添加学生信息...')

add_student('root')

结果:
登陆成功                ##先判断登陆
inspect_res的返回值为:{'name': 'root'}   ##判断是不是root
is root
添加学生信息...     ##最后执行返回值

猜你喜欢

转载自blog.csdn.net/qq_42036824/article/details/86592725