• 多个装饰器修饰一个函数时的调用顺序


    参考教程: https://blog.csdn.net/jyhhhhhhh/article/details/54627850

    #当有多个装饰器装饰一个函数时,他们的执行顺序
    
    #观察下方的代码就会发现
    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
    @decorator_a
    def f(x):
        #decorator_b(decorator_a(f))
        #而以上代码【decorator_b(decorator_a(f))】返回的是inner_b,所以执行的时候是先执行inner_b
        #然后在执行【decorator_a(f)】返回的inner_a  .最终在调用f(1)的时候,函数inner_b输出'Get in inner_b'
        #然后执行inner_a输出Get in decorator_a,最后执行func(),即f
        
        
        #调用时,函数的顺序
        '''
        @decorator_b
        @decorator_a
        def f(x)
        
        相当于-------decorator_b(decorator_a(f)),其中每一层返回的都是一个函数对象,没有调用
        之后返回时的函数对象--------inner_b(inner_a)
        然后最后一行当我们对 f 传入参数1进行调用时, inner_b 被调用了,它会先打印 Get in inner_b ,
        然后在 inner_b 内部调用了 inner_a 所以会再打印 Get in inner_a, 然后再 inner_a 内部调用的原来的 f, 
        并且将结果作为最终的返回
        '''
        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


    实际中的使用
    在实际应用的场景中,当我们采用上面的方式写了两个装饰方法,比如先验证有没有登录@login_required,
    再验证权限够不够时@permision_allowed时,我们采用下面的顺序来装饰函数:
    
    @login_required
    @permision_allowed
    def f()
      # Do something
    

      



  • 相关阅读:
    【转】RocketMQ事务消费和顺序消费详解
    RocketMQ初探(五)之RocketMQ4.2.6集群部署(单Master+双Master+2m+2s+async异步复制)
    Spring定时器Quartz的使用
    RocketMQ初探(四)之RocketMQ4.x版本可视化管理控制台rocketmq-console-ng搭建(Apache)
    RocketMQ入门(简介、特点)
    RocketMQ初探(二)之RocketMQ3.26版本搭建(含简单Demo测试案例)
    RocketMQ初探(一)
    tomcat详解
    HDFS读写流程
    RabbitMQ
  • 原文地址:https://www.cnblogs.com/qingsheng/p/9629668.html
Copyright © 2020-2023  润新知