装饰器
Posted beichen123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器相关的知识,希望对你有一定的参考价值。
装饰器
定义:
用来装饰的工具
在不改变源代码及调用方式的基础上额外增加新的功能
开放封闭原则:
扩展是开放的(增加新功能)
修改源码是封闭的(修改已经实现的功能)
版一:
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")
标准版:
def func(a): #a是要被装饰的函数名
def foo(*args,**kwargs):
"装饰之前的操作"
ret = a(*args,**kwargs)
"装饰之后的操作"
return ret
return foo
@func
def f1(*args,**kwargs):
print(f"这是一个args")
return "我可以返回了"
f1(1,2,3,34,4,5)
语法糖
语法糖必须放在被装饰的函数正上方
@wrapper 就等于 func = wrapper(func)
@wrapper 就等于 foo = wrapper(foo)
以上是关于装饰器的主要内容,如果未能解决你的问题,请参考以下文章