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)
    让火焰净化一切
  • 相关阅读:
    poj-1017 Packets (贪心)
    poj-2393 Yogurt factory (贪心)
    POJ -3190 Stall Reservations (贪心+优先队列)
    hihoCoder 1082然而沼跃鱼早就看穿了一切 (字符串处理)
    kafka:一个分布式消息系统
    Kafka+Storm+HDFS整合实践
    使用Storm实现实时大数据分析
    Kafka使用入门教程 简单介绍
    Zookeeper 的学习与运用
    Kafka 分布式消息队列介绍
  • 原文地址:https://www.cnblogs.com/icefoxhz/p/11608270.html
Copyright © 2011-2022 走看看