Python記錄11:疊加多個裝飾器+有參裝飾器
阿新 • • 發佈:2018-12-05
# import time
#
# def timmer(func): #func=最原始的index的記憶體地址
# def wrapper(*args,**kwargs):
# start=time.time()
# res=func(*args,**kwargs)
# stop=time.time()
# print(stop - start)
# return res
# return wrapper
#
# @timmer #index=timmer(index) #index=wrapper的記憶體地址
# def index():
# print('index function')
# time.sleep(1)
#
# index(1,2,3,) #wrapper(1,2,3)
# 疊加多個裝飾器
#1. 載入順序: 自下而上
#2. 執行順序
# import time
#
# def deco1(func1): #func1=wrapper2的記憶體地址
# # print('deco1執行')
# def wrapper1(*args,**kwargs):
# print('wrapper1')
# res=func1(*args,**kwargs)
# return res
# return wrapper1
#
# def deco2(func2): #func2=wrapper3的記憶體地址
# # print('deco2執行')
# def wrapper2(*args,**kwargs):
# print('wrapper2')
# res=func2(*args,**kwargs)
# return res
# return wrapper2
#
# def deco3(func3): #func3=最原始那個index的記憶體地址
# # print('deco3執行')
# def wrapper3(*args,**kwargs):
# print('wrapper3')
# res=func3(*args,**kwargs)
# return res
# return wrapper3
#
#
# # index=wrapper1
# @deco1 # index=deco1(wrapper2)
# @deco2 # wrapper2=deco2(wrapper3)
# @deco3 # wrapper3=deco3(最原始那個index的記憶體地址)
# def index():
# print('index function')
# time.sleep(1)
#
# index() #wrapper1()
import time
current_user={'username':None}
def timmer(func): #func=最原始的index的記憶體地址
def wrapper1(*args,**kwargs):
start=time.time()
res=func(*args,**kwargs) #================>wrapper2
stop=time.time()
print(stop - start)
return res
return wrapper1
def auth(func):
def wrapper2(*args,**kwargs):
if current_user['username']:
res = func(*args, **kwargs)
return res
name=input('username>>: ').strip()
pwd=input('password>>: ').strip()
if name == 'egon' and pwd == '123':
current_user['username']=name
res=func(*args,**kwargs)
return res
else:
print('賬號密碼錯誤...')
return wrapper2
@timmer
@auth
def index():
print('index function')
time.sleep(1)
index()
import time
current_user={'username':None}
def outter(engine='file'):
def auth(func):
def wrapper2(*args,**kwargs):
# if current_user['username']:
# res = func(*args, **kwargs)
# return res
name=input('username>>: ').strip()
pwd=input('password>>: ').strip()
if engine == 'file':
print('基於檔案的認證')
if name == 'egon' and pwd == '123':
current_user['username']=name
res=func(*args,**kwargs)
return res
else:
print('賬號密碼錯誤...')
elif engine == 'mysql':
print('基於mysql的認證')
elif engine == 'ldap':
print('基於ldap的認證')
else:
print("不合法的認證源")
return wrapper2
return auth
@outter(engine='file') # 賬號密碼是來自於檔案 index=aaa.txt(index) #index=wrapper2
def index():
print('index function')
time.sleep(1)
@outter(engine='mysql') # 賬號密碼是來自於mysql # home=bbb(home) #home=wrapper2
def home(name):
print('home function',name)
time.sleep(1)
index() #wrapper2()
home('egon') #wrapper2('egon')