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)
    让火焰净化一切
  • 相关阅读:
    java添加后台缓存
    Acunetix WVS安全测试软件使用教程(入门级)
    spring mvc + ajax上传文件,页面局部刷新
    github新手使用教程
    Junit使用方法
    反射(动态代理)
    TCP--文件上传
    网络编程--UDP通讯
    线程实现计时器,多线程间通信
    序列流
  • 原文地址:https://www.cnblogs.com/icefoxhz/p/11608270.html
Copyright © 2011-2022 走看看