装饰器
Posted x-h-15029451788
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器相关的知识,希望对你有一定的参考价值。
装饰器:
开放封闭原则:
1。代码扩展进行开放
2。修改源代码是封闭的
在不修改源代码及调用方式,对功能进行额外添加就是封闭原则
def index ():
print("这是个主页")
index()
修饰(额外功能) 器:工具(函数)
import time
def func():
time.sleep(1)
print("这是小刚写的功能")
def index():
time.sleep(2)
print("这是小刚写的功能")
def red():
time.sleep(3)
print("这是小红写的功能")
start_time = time.time()
index()
print(time.time() - start_time)
start_time = time.time()
func()
print(time.time() - start_time)
start_time = time.time()
red()
print(time.time() - start_time)
import time
def index():
time.sleep(2)
print("这是小明写的功能")
def func():
time.sleep(3)
print("这是李虎写的功能")
def red():
time.sleep(4)
print(‘这是建伟写的功能‘)
def times(func):
start_time = time.time()
func()
print(time.time()-start_time)
times(index)
times(func)
times(red)
import time
def index():
time.sleep(3)
print("建伟完事了")
def func():
time.sleep(1)
print("李虎完事了")
def red():
time.sleep(2)
print("种猪完事了")
def times(func):
start_time = time.time() # 时间戳
func()
print(time.time() - start_time)
f = index
index = times
index(f)
f1 = func
func = times
func(f1)
f2 = red
red = times
red(f2)
第一版装饰器
import time
def func():
time.sleep(1)
print("陈冠希完事了")
def red():
time.sleep(1)
print("王强完事了")
def index():
time.sleep(2)
print("胡斌完事了")
def times (func):
def foo ():
start_time =time.time()
func ()
print(time.time() - start_time)
return foo
index = times(index)
index()
func = times(func)
func()
red = times(red)
red()
def func():
print("被装饰的函数")
def warpper(f):
def inner():
print("111")
f()
print("222")
return inner
func = warpper(func)
func()
def warpper(f):
def inner():
print("111")
f()
print("222")
return inner
@warpper # func = warpper(func)
def func():
print("被装饰的函数1")
@warpper # index = warpper(index)
def index():
print("被装饰的函数2")
func()
def warpper(f):
def inner():
print("111")
f()
print("222")
return inner
@warpper # func = warpper(func)
def func():
print("被装饰的函数1")
@warpper # index = warpper(index)
def index():
print("被装饰的函数2")
# python帮咱们做的一个东西,语法糖
func()
index()
def warpper(f):
def inner(*args,**kwargs):
print("被装饰函数执行前")
ret = f(*args,**kwargs)
print("被装饰函数执行后")
return ret
return inner
@warpper#func = warpper(func)
def func(*args,**kwargs):
print(f"被装饰的args,kwargs")
return "我是func函数"
# func(1,2,3,4,5,6,7,8,a=1)
print(func(1,2,3,4,5,6,7,8,a=1))
@warpper
def index(*args,**kwargs):
print(11111)
index()
以上是关于装饰器的主要内容,如果未能解决你的问题,请参考以下文章