一、
前言:装饰器是基于函数的,装饰器是函数,函数却不一定是装饰器
二、
定义:
本质上是函数,但是他有特殊作用,用来装饰其他函数,给其他函数赋予新的功能
特点:
1.不能修改被装饰的函数的源代码
2.不能改变被装饰函数的调用方式
三、装饰器作用:
可以极大简化代码,避免每个函数编写重复性的代码
(1)、打印日志:@log
(2)、检测性能:@performance
(3)、数据库事务:@transaction
(4)、URL路由:@post(‘/register’)
四、定义自己先要执行的函数
1. def new_fn(要执行的函数名字):
2. def fn(要执行的参数函数参数/或者没有参数):
3. 添加要添加的函数功能
4. return f(x) 函数的执行结果
5. return fn
以下是实例:
1 2 3 4 5 6 7 8 9 10 11 12
| def simple_decorator(f): def wrapper(): print("开始") f() print("退出") return wrapper @simple_decorator #@语法糖 def hello(): print("我正在执行...") hello()
|
一、函数即变量:
1.函数也是一个对象,它也可以赋值变量,也可以通过变量调用函数
2.变量可以是参数
1 2 3 4
| def hello2(arg): print(arg) hello2(hello)
|
3.变量可以作为返回值
1 2 3 4
| def hello2(arg): return arg hello2(hello)()
|
二、高阶函数:(装饰器就是一个高阶函数)
1.以函数作为参数的函数
2.返回值是函数的函数
三、嵌套函数
函数里面定义函数
装饰器 = 高阶函数+嵌套函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import time def simple_decorator(f): def wrapper(): print("开始") f() print("退出") return wrapper @simple_decorator def hello(): time.sleep(1) print("我正在执行...") def get_time(foo): def inner(): s_time = time.time() foo() e_time = time.time() print('hello执行了%s秒' % (e_time - s_time)) return inner new_hello = get_time(hello) print(new_hello)
|
执行结果:<function get_time.<locals>.inner at 0x02B538A0> ``代表内部函数
new_hello()执行成功
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import time def simple_decorator(f): def wrapper(): print("开始") f() print("退出") return wrapper def get_time(foo): def inner(): s_time = time.time() foo() e_time = time.time() print('hello执行了%s秒' % (e_time - s_time)) return inner @get_time #等价于hello = get_time(hello) def hello(): time.sleep(1) print("我正在执行...") hello()
|