• python装饰器理解


    装饰器:

          在不改变原函数的代码和调用方法的基础上,给原函数增加额外的功能

    理解声明:为了方便理解,以下例子采用最简洁的函数和添加的功能(给原函数添加一个执行时间)

    import time 
    def timer(func):
        def inner():
            func()
        return inner
    
    
    @timer   # func = timer(func)
    def func():
        print('in the func')
    
    func()

    以上便实现了一个简单的装饰器

    带参数的装饰器

    flag = True   #设置一个简单的开关来更改之前的装饰器使用
    
    def outer(flag):
        def timer(func):
            def inner(*args, **kwargs):
                ret = func(*args, **kwargs)
                if flag:
                    print(time.time())
                return ret
    
            return inner
    
        return timer
    
    @outer(flag)  # outer(flag) = timer -> @timer
    def func1():
        print('func1')
    
    func1()
    
    flag = False
    
    func1()
        

    多个装饰器装饰一个函数

    def wrapper1(func):
        def inner(*args,**kwargs):
            print('warpper1 前')
            ret = func(*args, **kwargs)
            print('wrapper1 后')
            return ret
        return inner
    
    
    def wrapper2(func):
        def inner(*args,**kwargs):
            print('warpper2 前')
            ret = func(*args, **kwargs)
            print('wrapper2 后')
            return ret
        return inner
    
    
    @wrapper2    # func1 = wrapper2(func1) => inner
    @wrapper1    # func1 = wrapper(func1) => inner
    def func1():
        print('func1')
    
    func1()

    他们之间的关系:(同一种颜色表示他们本身等价)

    执行结果:

    解释器在解释的时候先装饰靠近函数的装饰器

    结构图:

  • 相关阅读:
    zoj 1004 Anagrams by Stack (dfs+stack)
    poj 3009 Curling 2.0 (dfs)
    poj 2965 The Pilots Brothers' refrigerator (bfs+位运算)
    bcl 1387 最长重复子串 (后缀数组)
    zoj 3332 Strange Country II (dfs)
    poj 2157 Maze (bfs)
    poj 1564 && zoj 1711 Sum It Up (dfs)
    hdu 2686 Matrix (多进程DP)
    poj 3256 Cow Picnic (dfs)
    poj 1606 Jugs (bfs)
  • 原文地址:https://www.cnblogs.com/Wj-Li/p/10864912.html
Copyright © 2020-2023  润新知