• python--装饰器


    函数即变量

    def out(func):   #函数名作为变量传进来
        func()     #调用函数 函数在没调用的时候就是一个字符串
    
    def demo():
        print(111)
    
    out(demo)

    嵌套函数

    嵌套函数的参数作用域:由内到外查找

    def out():
        name='aaa'
        def inner():
            name='bbb'
            print(name)
        inner()
        print(name)
    
    out()

    装饰器

    装饰器的本质还是一个函数

    在不改变函数调用方式的情况下,给函数额外添加功能

    # 需求:给项目中每一个函数增加函数执行时间
    
    #改变了函数调用方式时
    import time
    def demo():
        print('hahaha')
    
    def out(func):
        def inner():
            start =time.time()
            func()
            end = time.time()
            print(end-start)
        return inner
    
    demo =out(demo)
    demo()
    #用装饰器,不改变函数调用方式
    import time
    def out(func):
        def inner(*args,**kwargs):
            start =time.time()
            func(*args,**kwargs)
            end = time.time()
            print(end-start)
        return inner           
    
    @out    #相当于out(demo)
    def demo(name):
        print(name)
    
    demo('123')
    #一个装饰器添加多个功能
    import time
    def auto(a):
        if a==1:
            def out(func):
                def inner(*args, **kwargs):
                    start = time.time()
                    func(*args, **kwargs)
                    end = time.time()
                    print(end - start)
                return inner
            return out
        elif a==2:
            pass
    
    @auto(1)
    def demo(name):
        print(name)
    
    demo('hehehe')
  • 相关阅读:
    使用Anaconda安装TensorFlow
    更新pip源/anaconda源
    PHP 中 config.m4 的探索
    有趣的智力题
    工作中MySql的了解到的小技巧
    一篇关于PHP性能的文章
    eslasticsearch操作集锦
    curl 命令详解~~
    Nginx 调优经验记录
    Elasticsearch安装使用
  • 原文地址:https://www.cnblogs.com/HathawayLee/p/9895085.html
Copyright © 2020-2023  润新知