装饰器:本质仍是函数,用来装饰目标函数的函数。
使用环境:在不改变源代码的前提下,对原函数添加新的功能。
使用原则:1、不改变源代码;
2、不改变原函数调用方式;
工作原理:1、将目标函数做为参数传入装饰器(decorator)函数中;
2、在装饰器(decorator)函数中,在调用目标函数之前或之后,调用附加功能的函数来装饰目标
函数,然后调用目标函数,并返回结果,起到装饰作用。
装饰器函数又分以下几种:
1、目标函数带参数与不带参数;
import time
# 目标函数不带参数
def decorator(func):
def wrapper():
start_time = time.time()
time.sleep(3)
func()
stop_time = time.time()
print("test run time is %d" % (start_time - stop_time))
return wrapper
@decorator # 相当于 test = decorator(test)
def test():
print("run test")
test()
print("我是分割线".center(40, "*"))
# 目标函数带参数
def decorator1(func):
def wrapper(*args, **kwargs):
start_time = time.time()
time.sleep(5)
func(*args, **kwargs)
stop_time = time.time()
print("test1 run time is %d" % (start_time - stop_time))
return wrapper
@decorator1 # 相当于 test1 = decorator1(test1)
def test1(name, age=26):
print("run test1")
print("%s is %d year old" % (name, age))
test1("Jack")
运行结果:
>>> ================================ RESTART ================================
>>>
run test
test run time is -3
*****************我是分割线******************
run test1
Jack is 26 year old
test1 run time is -5
*****************我是分割线******************
>>>
2、装饰器函数带参数与不带参数;
对于无参数的装饰器,其装饰器函数的参数是要被装饰的函数对象名;
对于有参数的装饰器在调用时使用的是应用的参数
对于装饰器带参数,比较迷惑,这里放上参考链接:
http://blog.youkuaiyun.com/dreamcoding/article/details/8611578