装饰器
定义:
用来装饰的工具
在不改变源代码及调用方式的基础下额外增加新的功能
开放封闭原则:
扩展是开放的(增加新功能)
修改源码是封闭的(修改已经实现的功能)
版一:
import time
start_time = time.time()
def func():
time.sleep(2)
print("asdf")
func()
print(time.time() - start_time)
start_time = time.time()
def foo():
time.sleep(3)
print("qwer")
foo()
print(time.time() - start_time)
版二:
def times(f):
start_time = time.time()
f()
print(time.time() - start_time)
def foo():
time.sleep(3)
print("asdf")
s = foo
foo = times
foo(s)
版三(初识版装饰器):
def times(f):
def inner():
start_time = time.time()
f()
print(time.time() - start_time)
return inner
def foo():
time.sleep(1)
print("asdf")
foo = times(foo)
foo()
版四(第二版装饰器):
def wrapper():
def inner():
print(1)
return inner
print(wrapper()())
def wrapper(f):
def inner():
f()
return inner
def func():
print("123456")
func = wrapper(func)
func()
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,kwargs}函数")
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,kwargs}函数")
time.sleep(2)
@wrapper
def foo(*args,**kwargs):
print(f"这是{args,kwargs}函数,123456")
time.sleep(3)
func("alex","ahfe")
foo("alex1","faikewfhn")
语法糖
语法糖必须放在被装饰的函数正上方