Python 装饰器

1、开放封闭原则:对扩展开放、对修改是封闭
2、装饰器:装饰它人的,器指的是任意可调用对象,现在的场景装饰器(函数)
被装饰的对象也是函数
原则:1、不修改装饰对象的源代码;2、不修改被装饰对象的调用方式
装饰器的目的:在遵循1,2的前提下为被装饰对象添加上新功能

一、无参装饰器
import time
def timmer(func):
def inner():
start = time.time()
func()
end = time.time()
print("run time is %s" %(end - start))
return inner

@timmer #相当于index = timmer(index)
def index():
time.sleep(3)
print("welcome to index")

index() #相当于inner()
输出结果:welcome to index
run time is 3.0010766983032227


改进一:
import time
def timmer(func):
def inner():
start = time.time()
res = func()
end = time.time()
print("run time is %s" %(end - start))
return res
return inner

@timmer 相当于index = timmer(index)
def index():
time.sleep(3)
print("welcome to index")
return 1111

res = index() #相当于res = inner()
print(res)
输出结果:welcome to index
run time is 3.0010766983032227
1111

改进二:
import time
def timmer(func):
def inner(*args,**kwargs):
start = time.time()
res = func(*args,**kwargs)
end = time.time()
print("run time is %s" %(end - start))
return res
return inner

@timmer #相当于index = timmer(index)
def index(name):
time.sleep(3)
print("welcome %s to index" %name)
return 1111

res = index('keke') #相当于res = inner('keke')
print(res)
输出结果:welcome keke to index
run time is 3.000697135925293
1111

二、有参装饰器
import time
def outter(file):
def welcome(func):
def inner():
name = input("name>>:").strip()
res = func(name)
if file == 'mysql':
print("mysql")
elif file == 'mangodb':
print('mangodb')
else:
print('others!!!')
return res
return inner
return welcome

@outter(file='mangodb') 相当于@welcome index=welcome(index)
def index(name):
time.sleep(3)
print('welcome %s to index' %name)
return 1111

res = index()
print(res)

输出结果:name>>:keke
welcome keke to index
mangodb
1111





posted @ 2020-08-15 17:05  冰箱喵  阅读(133)  评论(0编辑  收藏  举报