PYTHON装饰器用法及演变

时间:2024-09-06 22:35:20
'''
开放封闭原则:
软件一旦上线之后就应该满足开放封闭原则
具体就是指对修改是封闭的,对扩展是开放的
装饰器:
什么是装饰器:装饰就是修饰,器指的是工具
装饰器本省可以是任意可调用的对象
被装饰的对象也可以是任意可以被调用的对象 装饰器====》可以是一个函数
被装饰对象====》也可以是一个函数
装饰器就是用来为被装饰对象修改添加新功能的一种工具
必须遵循两个原则:
1,不能修改被装饰对象的源代码
2,不能修改被装饰对象的调用方式 ###简单版本的装饰器:这种简单的装饰器只适用于没有参数没有返回值的情况
'''
import time
'''
def indes():
start_time = time.time()
time.sleep(1)
print('welcome to index')
end_time = time.time()
print('runtime is %s' %(end_time-start_time))
#
# # indes()
# def wrapper(func):
# start_time = time.time()
# func()
# end_time = time.time()
# run_time = end_time-start_time
# print(run_time)
# # wrapper(indes)
# def home():
# pass
# # wrapper(home)
#
def outer(func):
# func = indes
def wrapper():
start_time = time.time()
func()
end_time = time.time()
run_time = end_time-start_time
print(run_time)
return wrapper
indes = outer(indes)####f = wrapper
res = indes()
print(res)
'''
# print('='*100)
# def outer():
# def wrapper():
# start_time = time.time()
# return 123
# print("hello world")
# end_time = time.time()
# print('运行时间是%s' %(end_time - start_time))
# return wrapper
# res = outer()
# print(res())
###装饰器进阶版:
'''
import time
def home(name):
time.sleep(2)
print("welcome to home page")
return 1234 def timmer(func):
def inner(*args,**kwargs):
start_time = time.time()
res = func(*args,**kwargs)
end_time = time.time()
print('运行时间是%s' %(end_time - start_time))
return res
return inner home = timmer(home)
home('egon')
'''
'''
装饰器语法糖:
在被装饰对象正上方单独一行写:
@装饰器的名字 意思也就是: 被装饰对象 = 装饰器的名字(被装饰对象)
注意:新定义的装饰器函数必须放在要装饰的函数的上方,也就是给要装饰的函数带个帽子 最终的版本是:
'''
'''
import time def timmer(func):####装饰器函数
def inner(*args,**kwargs):
start_time = time.time()
res = func(*args,**kwargs)
end_time = time.time()
print('运行时间是%s' %(end_time - start_time))
return res
return inner
@timmer
###被装饰的对象
def home(name):
time.sleep(2)
print("welcome to home page")
return 1234 # home = timmer(home)
home('egon')
'''
'''
import time def outer(func):
def wrapper(*args,**kwargs):####这里的参数情况要和被装饰的对象一致
user_name = input('please input user name =====>')
pwd = input('please input pass word======>')
if user_name =='egon' and pwd == '123':
res = func(*args,**kwargs)
return res
return wrapper
@outer
def index():
time.sleep(1)
print('welcome to index page ')
return 1234 def home(name):
time.sleep(2)
print('welcome %s to home page ' %name ) index()
'''
####有参装饰器
##有带参数的装饰器,这个是最高难度的,一般也只需要像这样套三层。
import time
def anth(engine = 'file'):###默认参数设置为file
def outer(func):
def wrapper(*args,**kwargs):####这里的参数情况要和被装饰的对象一致
user_name = input('please input user name =====>')
pwd = input('please input pass word======>')
if engine == 'file':
if user_name =='egon' and pwd == '123':
res = func(*args,**kwargs)
return res
elif engine =='mysql':
print("基于mysql的认证")
elif engine == 'ldap':
print('基于lasp的认证') return wrapper
return outer
ot = anth(engine = 'mysql')
@ot
def index():
time.sleep(1)
print('welcome to index page ')
return 1234 def home(name):
time.sleep(2)
print('welcome %s to home page ' %name ) index()