zoukankan      html  css  js  c++  java
  • 装饰器

    定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能。

    原则:1.不能修改被装饰的函数的源代码;

               2.不能修改被装饰函数的调用方式。

    理解装饰器需理解一下三点:

    1.函数即变量

      函数同其他变量一样,在声明的时候都是把内容(字符串的形式)放进内存中,函数名(变量名)作为此内容的“门牌号”。

    2.高阶函数

    3.嵌套函数

    最简单的装饰器案例

    #coding=utf-8
    
    import time
    
    def decorator(func):
        def wrapper():
            start_time = time.time()
            func()
            end_time = time.time()
            print '执行所花时间:', end_time - start_time
        return wrapper
    
    @decorator # 相当于test = decorator(test)
    def test():
        print '执行...'
        time.sleep(3)
    
    test()

    被装饰的函数传参

    #coding=utf-8
    
    import time
    
    def decorator(func):
        def wrapper(*args, **kwargs):
            start_time = time.time()
            func(*args, **kwargs)
            end_time = time.time()
            print '执行所花时间:', end_time - start_time
        return wrapper
    
    @decorator # 相当于test = decorator(test) = wrapper  => test() = wrapper()
    def test(second):
        print '执行...'
        time.sleep(second)
    
    test(1)

    装饰器传参(再最外面再加一层)

    #coding=utf-8
    
    import time
    
    def decorator(show_time):
        def out_wrapper(func):
            def wrapper(*args, **kwargs):
                start_time = time.time()
                func(*args, **kwargs)
                end_time = time.time()
                print '执行所花时间:', end_time - start_time
                if show_time:
                    print '当前时间:', time.strftime("%Y-%m-%d %X", time.localtime())
            return wrapper
        return out_wrapper
    
    @decorator(True)
    def test(second):
        print '执行...'
        time.sleep(second)
    
    test(1)
  • 相关阅读:
    C# 文件类的操作---删除
    C#实现Zip压缩解压实例
    UVALIVE 2431 Binary Stirling Numbers
    UVA 10570 meeting with aliens
    UVA 306 Cipher
    UVA 10994 Simple Addition
    UVA 696 How Many Knights
    UVA 10205 Stack 'em Up
    UVA 11125 Arrange Some Marbles
    UVA 10912 Simple Minded Hashing
  • 原文地址:https://www.cnblogs.com/allenzhang-920/p/8900128.html
Copyright © 2011-2022 走看看