装饰器
开放封闭原则:
1.拓展是开放的(增加新功能)
2.修改源码是封闭的(修改已经实现的功能)
装饰器:
用来装饰的工具
在不改变源代码及调用方式的基础上额外增加新的功能
版本一
import time
start_time = time.time()
def func():
time.sleep(2) #睡眠,模拟网络延时
print("我要飞")
func()
print(time.time() - start_time)
start_time = time.time()
def foo():
time.sleep(3)
print("我是小明,我飞的比你高")
foo()
print(time.time() - start_time)
版本二
import time
def times(f):
start_time = time.time()
f()
print(time.time() - start_time)
def foo():
time.sleep(3)
print("我是小明,我飞的比你高")
def func():
time.sleep(1)
print("我是小刚,我飞不起来")
s = func
func = times
func(s)
s = foo
foo = times
foo(s)
版本三(初识版装饰器)
import time
def times(f):
def inner():
start_time = time.time()
f()
print(time.time() - start_time)
return inner
def foo():
time.sleep(1)
print("我要飞")
foo = times(foo)
foo()
版本四(第四版装饰器)
def wrapper():
def inner():
print(1)
return inner
wrapper()
def wrapper(f):
def inner():
print(f)
return inner
wrapper("alex")
def wrapper(f):
def inner():
f()
return inner
def func():
print("这是func函数")
func = wrapper(func)
func()
def wrapper(f):
def inner(*args,**kwargs):
f(*args,**kwargs)
return inner
def func(*args,**kwargs):
print(f"这是{args}函数")
func = wrapper(func)
func("alex","wusir")
low版:
import time
def wrapper(f):
def inner(*args,**kwargs):
#被装饰前#
start_time = time.time()
f(*args,**kwargs)
print(time.time() - start_time)
#被装时后#
return inner
def func(*args.**kwargs):
print(f"这是{args}函数")
time.sleep(2)
func = wrapper(func)
func("alex","wusir")
高级:
import time
def wrapper(f):
def inner(*args,**kwargs):
#被装饰前#
start_time = time.time()
f(*args,**kwargs)
print(time.time() - start_time)
#被装饰后#
return inner
@wrapper
def func(*args,**kwargs):
print(f"这是{args}函数a")
time.sleep(2)
@wrapper
def foo(*args,**kwargs):
print(f"这是{args}函数b")
time.sleep(3)
func("alex","wusir")
foo("alex","wusir")
语法糖
语法糖必须放在被装饰的函数正上方
import time
def wrapper(f):
def inner(*args,**kwargs):
#被装饰前#
start_time= time.time()
ret = f(*args,**kwargs)
print(time.time() - start_time)
#被装饰后#
return retre
return inner
@wrapper
def func(*args,**kwargs):
print(f"这是{args}函数")
time.sleep(2)
return "alex"
print(func())