zoukankan      html  css  js  c++  java
  • 多个装饰器执行顺序

    多个装饰器的执行顺序

    def decorator_a(func):
        print 'Get in decorator_a'
        def inner_a(*args, **kwargs):
            print 'Get in inner_a'
            return func(*args, **kwargs)
        return inner_a
    
    def decorator_b(func):
        print 'Get in decorator_b'
        def inner_b(*args, **kwargs):
            print 'Get in inner_b'
            return func(*args, **kwargs)
        return inner_b
    
    @decorator_b#f=decorator_b(f)
    @decorator_a#f=decorator_a(f)
    def f(x):
        print 'Get in f'
        return x * 2

    """

    Get in decorator_a
    Get in decorator_b

    """

    等同于

    def decorator_a(func):
        print('Get in decorator_a')
        def inner_a(*args, **kwargs):
            print('Get in inner_a')
            return func(*args, **kwargs)
        return inner_a
    
    def decorator_b(func):
        print('Get in decorator_b')
        def inner_b(*args, **kwargs):
            print('Get in inner_b')
            return func(*args, **kwargs)
        return inner_b
    
    def f(x):
        print('Get in f')
        return x * 2
    
    
    f=decorator_a(f)
    f=decorator_b(f)




    """

    Get in decorator_a
    Get in decorator_b

    """

    得出结论 装饰器函数在被装饰函数定义好后立即执行 并且是从下往上执行,最后的两句代码等同于

    f=decorator_b(decorator_a(f)),执行顺序是从里到外,最先调用最里层的装饰器,最后调用最外层的装饰器

    def decorator_a(func):
        print('Get in decorator_a')
        def inner_a(*args, **kwargs):
            print('Get in inner_a')
            return func(*args, **kwargs)
        return inner_a
    
    def decorator_b(func):
        print('Get in decorator_b')
        def inner_b(*args, **kwargs):
            print('Get in inner_b')
            return func(*args, **kwargs)
        return inner_b
    
    @decorator_b#f=decorator_b(f)
    @decorator_a#f=decorator_a(f)
    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
    """

    当我们对f传入参数1进行调用时,inner_b被调用了,他会先打印Get in inner_b,然后在inner_b内部调用了inner_a,所以会再打印Get in inner_a,然后再inner_a内部调用原来的f,并且将结果作为最终的返回

    总结:

    装饰器函数在被装饰函数定义好后立即执行从下往上执行

    函数调用时从上到下执行

    实际应用过程中,先验证有没有登录,在验证权限够不够,采用从上到下的顺序来装饰函数

    @login_required
    @permision_allowed
    def f()
      # Do something
      return
  • 相关阅读:
    SpringCloud学习系列之四-----配置中心(Config)使用详解
    阿里云Docker镜像仓库(Docker Registry)
    阿里云Docker镜像加速
    Docker安装(yum方式 centos7)
    Docker Nginx安装(centos7)
    Dockerfile文件详解
    mysql 开发进阶篇系列 6 锁问题(事务与隔离级别介绍)
    mysql 开发进阶篇系列 5 SQL 优化(表优化)
    mysql 开发进阶篇系列 4 SQL 优化(各种优化方法点)
    sql server 性能调优之 资源等待PAGELATCH
  • 原文地址:https://www.cnblogs.com/z-x-y/p/9157238.html
Copyright © 2011-2022 走看看