zoukankan      html  css  js  c++  java
  • 闭包、装饰器、高阶函数

    装饰器

    # 装饰器的本质是函数,为某函数提供额外功能(原则:1 不能修改某函数代码   2 不能修改某函数调用方式, 就是说某函数原来怎么用,装饰完还是怎么用)

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

    -----------------------------------------------------------------------

    高阶函数:

    1. 函数接收参数是一个函数名

    2. 函数返回值是一个函数名

    满足以上任意一个条件,就是高阶函数

    例1:

    def fun1():
    print("fun1")

    def test(fun):
    fun()

    test(fun1)

    例2:

    def fun1():
    print("fun1")

    def test(fun):
    return fun

    res = test(fun1)
    res()

    -----------------------------------------------------------------------

    闭包

    -----------------------------------------------------------------------

    装饰器 

    Example1:

    import time

    def timer(fun):
    def myRun():
    time1 = time.time()
    fun()
    time2 = time.time()
    print("运行时间:", time2 - time1)
    return myRun

    @timer #相当于做了 test = timer(test)
    def test():
    time.sleep(2)
    print('run over')

    test()

     Example2:

    import time

    def timer(fun):
    def myRun(*args, **kwargs):
    time1 = time.time()
    res = fun(*args, **kwargs)
    time2 = time.time()
    print("运行时间:", time2 - time1)
    return res
    return myRun

    @timer #相当于做了 test = timer(test)
    def test(name):
    time.sleep(2)
    print('run over')
    return 'name:' + name

    @timer #相当于做了 test1 = timer(test1)
    def test1(name, age):
    time.sleep(2)
    print('run over')
    return 'name:' + name + ", age:" + age

    res = test('saber')
    print(res)

    res = test1('saber', '22')
    print(res)
    让火焰净化一切
  • 相关阅读:
    1058 A+B in Hogwarts (20)
    1046 Shortest Distance (20)
    1061 Dating (20)
    1041 Be Unique (20)
    1015 Reversible Primes (20)(20 分)
    pat 1027 Colors in Mars (20)
    PAT 1008 Elevator (20)
    操作系统 死锁
    Ajax的get方式传值 避免& 与= 号
    让IE浏览器支持CSS3表现
  • 原文地址:https://www.cnblogs.com/icefoxhz/p/11608270.html
Copyright © 2011-2022 走看看