zoukankan      html  css  js  c++  java
  • 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')
  • 相关阅读:
    Java操作Excel之POI简单例子
    机器学习之KNN算法
    机器学习之sklearn数据集
    数据分析之matplotlib
    数据分析之pandas
    数据分析之numpy
    python模块contextlib
    前端jsonp解决跨域问题
    django media和static配置
    Django之数据库迁移和创建
  • 原文地址:https://www.cnblogs.com/HathawayLee/p/9895085.html
Copyright © 2011-2022 走看看