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

    1.装饰器

    本质是函数,功能是为其他函数添加附加功能

    原则:1.不修改被装饰函数的源代码

                2.不修改被修饰函数的调用方式

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

    #装饰器格式框架
    def wrap(func):
    def wrapper(*args,**kwargs):
    func(*args,**kwargs)
    return wrapper

    2.高阶函数

    含义:1.函数接受参数的是一个函数

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

               3.满足上面任一条件都是高阶函数

    # 高阶函数
    import time

    def hello():
    time.sleep(3)
    print('hello world')

    def timer(func):
    start_time = time.time()
    func()
    end_time = time.time()
    print('函数运行时间是:%s' % (end_time - start_time))
    return func


    t = timer(hello)
    t()

    # 装饰器写法
    def total_time(func):
    def wrapper(*args, **kwargs):
    start_time = time.time()
    res = func(*args, **kwargs)
    stop_time = time.time()
    print("函数运行时间:%s" %(stop_time-start_time))
    return res
    return wrapper

    # @后面装饰器 作用于下面 相对于hello = total_time(hello)
    @total_time
    def hello():
    time.sleep(2)
    print("hello world")
      return "hello"

    h = hello()
    print(h)

    #显示
    # hello world
    # 函数运行时间:2.000795364379883
    # 2.000795364379883



  • 相关阅读:
    域名和dns
    Oracle版本区别及版本选择!
    并发
    URL和URI的区别??
    sshpass免密码(免交互)连接
    python之路 目录
    awk sed 总结
    aiohttp使用
    Mac破解软件 “XXX”意外退出 奔溃解决方法
    我的Mac中毒了,病毒居然叫做MacPerformance
  • 原文地址:https://www.cnblogs.com/icemonkey/p/10439702.html
Copyright © 2011-2022 走看看