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



  • 相关阅读:
    MySql锁机制
    Mysql存储引擎
    Linux 系统中安装mysql
    常见的系统架构
    Linux环境下搭建go开发环境
    Ajax概述
    正向代理和反向代理
    Mysql 存储过程以及在.net中的应用示例
    Mysql 事务
    Windows服务器实现自动化部署-Jenkins
  • 原文地址:https://www.cnblogs.com/icemonkey/p/10439702.html
Copyright © 2011-2022 走看看