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

    一 什么是装饰器

    器即函数,

    装饰即修饰,意指为其他函数添加功能

    装饰器定义:本质就是函数,功能是为其他函数添加新功能

    原则:

    • 不修改被修饰函数的源代码
    • 不修改被修饰函数的调用方式

    装饰器的基础知识:

      装饰器 = 高阶函数 + 函数嵌套 + 闭包

    二 高级函数

    高阶函数的定义:

    1. 函数接收的参数是一个函数名
    2. 函数的返回值是一个函数名
    3. 满足上面条件任意一个,都可以称之为高阶函数
     1 import time
     2 def test(fun):
     3     start_t = time.time()
     4     fun()
     5     stop_t = time.time()
     6     print("函数运行时间-->",stop_t - start_t)
     7 
     8 def foo():
     9     time.sleep(2)
    10     print("来自foo")
    11 test(foo)
    12 函数运行时间--> 2.0003068447113037
    13 """
    14 来自foo
    15 函数运行时间--> 2.0003068447113037
    16 """
    函数的参数是一个函数名
     1 import time
     2 def test(fun):
     3     start_t = time.time()
     4     fun()
     5     stop_t = time.time()
     6     print("函数运行时间-->",stop_t - start_t)
     7     return fun
     8 
     9 def foo():
    10     time.sleep(2)
    11     print("来自foo")
    12 
    13 foo = test(foo)
    14 foo()
    15 
    16 """
    17 来自foo
    18 函数运行时间--> 2.000347137451172
    19 """
    函数的返回值是一个函数名

    高阶函数终结

    1,函数接收的参数是一个函数名

      作用:在不修改函数源代码的前提下,为函数增加新功能

      不足:会改变函数的调用方式

    2,函数的返回值是一个函数名

      作用:不修改函数的调用方式

      不足:不能增添新功能

    三 函数的嵌套

    def father(name):
        print("from father %s"%name)
        def son():
            name = "abc"
            print("from son")
            def grandson():
                print("from grandson %s"%name)
            grandson()
        son()
    
    father("123")

    四 闭包

    在一个作用域里放入定义变量,相当于打了一个包

    五 装饰器的基本实现

    import time
    def test(fun):
        def wrapper(*args, **kwargs):
            start_t = time.time()
            res = fun(*args, **kwargs)
            stop_t = time.time()
            print("函数运行时间-->",stop_t - start_t)
            return res
        return wrapper
    
    @test # foo = test(foo)
    def foo(name,age):
        time.sleep(2)
        print("来自foo")
        return "这是test的返回值%s,%s"%(name,age)
    
    print(foo("abc",123))

     六 解压序列

    a = 1
    b = 2
    print(a,b)
    a,b = b,a
    print(a,b)
    """
    1 2
    2 1
    """
    
    l = (1,2,3,4,5,6)
    a,*b,c = l
    print(a,b,c)
    """
    1 [2, 3, 4, 5] 6
    """

    满足一一对应关系

  • 相关阅读:
    Programmatically parsing Transact SQL (TSQL) with the ScriptDom parser
    How to check for a valid Base64 encoded string
    三角函数和反三角函数
    Preventing User Enumeration on Registration Page
    创建HyperV虚拟机安装Win10教程详解
    爆强,看看PS高手怎么变出一个美女来
    用baidu搜索“sb”会出来什么结果?baidu也太狠了吧
    一组Opeth(月亮之城)的现场视频
    为了节约成本,要在西游记团队中栽一个你会裁掉哪位?
    Ruby on rails开发从头来(windows)(四)第一个添删查改例子
  • 原文地址:https://www.cnblogs.com/kaixindexiaocao/p/9757195.html
Copyright © 2011-2022 走看看