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)
    让火焰净化一切
  • 相关阅读:
    【STM32F429】第4章 RTX5操作系统移植(MDK AC5)
    【STM32F407】第4章 RTX5操作系统移植(MDK AC5)
    【STM32H7】第3章 RTX5操作系统介绍
    【STM32F429】第3章 RTX5操作系统介绍
    【STM32F407】第3章 RTX5操作系统介绍
    【STM32H7】第2章 初学RTX5准备工作
    【STM32F429】第2章 初学RTX5准备工作
    Hystrix解析(一)
    Eureka源码解析(五)
    Eureka源码分析(四)
  • 原文地址:https://www.cnblogs.com/icefoxhz/p/11608270.html
Copyright © 2011-2022 走看看