zoukankan      html  css  js  c++  java
  • Python 装饰器备忘

    def deco(attr):
        ''' 装饰器,共包含三层返回结构 
    
            第一层:用于接收 @deco 的参数,此处的代码只在初始化装饰器时执行一次 
    
            第二层:用于接收 function,此处的代码只在初始化装饰器时执行一次 
    
            第三层:用于接收 function 的参数,并将作为最终被执行与返回的装饰结果 
    
        '''
        def _deco(f):
            '''第二层:用于接收 function,此处的代码只在初始化装饰器时执行一次
            '''
            print('只在装饰函数时,执行一次,此时装饰函数', f.__name__)
    
            def __deco(a, b):
                '''第三层:用于接收 function 的参数,并将作为最终被执行与返回的装饰结果
                '''
                print('before run attr: ' + attr + '; a: ' + a + '; b: ' + b)
                # 此处必须调用 function,不然装饰器执行过后,就不会再执行 function 的函数体
                f(a, b)
                print('after  run attr: ' + attr + '; a: ' + a + '; b: ' + b)
    
            return __deco
        return _deco
    
    
    @deco('hello')
    def hello(a, b):
        print('hello, ' + a + b)
    
    
    @deco('world')
    def world(a, b):
        print('world, ' + a + b)
    
    
    hello('a', 'b')
    world('A', 'B')
    
    
    # 执行结果:
    # 
    # 只在装饰函数时,执行一次,此时装饰函数 hello
    # 只在装饰函数时,执行一次,此时装饰函数 world
    # before run attr: hello; a: a; b: b
    # hello, ab
    # after  run attr: hello; a: a; b: b
    # before run attr: world; a: A; b: B
    # world, AB
    # after  run attr: world; a: A; b: B
    
  • 相关阅读:
    NOIP 2016 提高组 复赛 Day2T1==洛谷2822 组合数问题
    Codevs 1710 == POJ 1190 生日蛋糕 == 洛谷P1731
    [网络流24题] COGS 750 栅格网络流
    [网络流24题] COGS 运输问题1
    狂K 线段树
    Graph coloring技能树
    智能体大赛酱油记
    graph coloring学习记录
    湖北省赛酱油记
    CCCC酱油记
  • 原文地址:https://www.cnblogs.com/sitemanager/p/9335621.html
Copyright © 2011-2022 走看看