介绍
本质
装饰器本质就是函数,功能是为其他函数添加附加功能
原则
- 不修改被修饰函数的源代码
- 不修改被修饰函数的调用方式
知识储备
装饰器 = 高阶函数 + 函数嵌套 + 闭包
-
高阶函数:
- 高阶函数的参数是一个函数名。
- 函数的返回值是一个函数名
- 满足以上两个条件任意一个,都可以称之为高阶函数 函数嵌套
- 在函数内部,定义其他函数
-
示例如下
def father(name): print('this father floor') def son(): print('this is son floor')
闭包
-
在一个作用域里定义一个封闭的local 变量
def father(name): print('this father : %s' %name) def son(): print('my father is : %s' % name) # grandson() 本质也是一个变量,是son下的一个封闭的变量 def grandson(): # 这里的name,是封闭包中的变量,外层不能调用 name='Tom' print('grandson is : %s' % name) grandson() son() father('evan')
装饰器示例
装饰器函数
import time
# 如果需要带参数进装饰器,可以在此函数之外再套一层函数,用来接收参数,并且在调用的时候,加入参数
# 例:
# def run_time_c(type='YMD')
# @run_time.run_time_c(type='DMY')
def run_time_cal(func):
def wrapper(*arg, **kwargs):
start_time = time.time()
res = func(*arg, **kwargs)
stop_time = time.time()
print('run time is %s ' % (stop_time - start_time))
return res
return wrapper
调用函数
import time
import sys
from first_package.Decorator_pkg import run_time
# 此处采用模块调用方式调用装饰器
@run_time.run_time_cal
def run_time_test(name, age):
print('user name : %s' % name)
time.sleep(2)
print('user age : %s' % age)
if __name__ == '__main__':
print(sys.path)
run_time_test(123, 'hello')