装饰器

装饰器的作用:

  • 不能修改被装饰的函数的源代码;
  • 不能修改被装饰的函数的调用方式;
  • 满足1、2的情况下给程序增添功能;

装饰器公式 = 函数 + 实参函数 + 返回值函数 + 嵌套函数 + 语法糖(@)


需求1:打印一个函数,并统计三个函数的运行时间;
(函数的用法)

from time import time,sleep
def fun_one():
    start = time()
    sleep(2)
    end = time()
    cost_time = end - start
    print("func one run time {}" .format(cost_time))
fun_one=fun_one()
fun_one

运行结果如下:

func one run time 2.0015718936920166

通过sleep停止两秒后运行print,并打印cost_time值;


需求2:打印两个函数,并统计运行时间;
(高阶函数)

from time import time,sleep
def fun_one():
    sleep(2)
def fun_two():
    sleep(2)
def demo(func):
    start = time()
    func()
    end = time()
    cost_time = end - start
    print("func in running {}".format(cost_time))

fun_one=demo(fun_one)
fun_two=demo(fun_two)
fun_one
fun_two

运行过程:

  • 将fun_one作为func传参到demo;
  • demo先记录start_time,然后运行func时去找到fun_one,会sleep2秒;
  • 接着往下走记录end_time,最后统计运行时间并print;
  • 整个函数运行结果传给fun_one;

运行结果如下:

func in running 2.002671241760254
func in running 2.0035440921783447

将两个函数的代码重复部分单独列出来,传参到demo后print每个函数的运行时间;


posted @ 2021-10-28 11:07  红茶课堂  阅读(35)  评论(0)    收藏  举报