Python学习week4
装饰器:本质是函数,用来装饰其他的函数,为其它函数添加附加功能。 原则:不能改变被装饰函数的源代码和调用方式。 1、函数即‘变量’,定义一个函数相当于把函数体赋值给函数名,匿名函数相当于只有函数体没有函数名 def func1(): print('in the function') func2=func1 #和普通的整数赋值一样:a=2 b=a print(b) func2() 2、高阶函数 3、嵌套函数 装饰器=高阶函数+嵌套函数 高阶函数: 1、把一个函数名当作实参传递给另外一个函数;(在不修改被装饰函数源代码的情况下为其添加功能) 2、返回值中包含函数名。(不修改函数的调用方式) import time def bar(): time.sleep(2) print('in the bar') def timer(func): start_time=time.time() func() stop_time=time.time() print('the time of running is %s'%(stop_time-start_time)) timer(bar) 输出: in the bar the time of running is 2.0002079010009766 函数执行计时器 import time def bar(): time.sleep(2) print(