11.41 多層裝飾器
阿新 • • 發佈:2022-03-24
import time
user_dic = {'is_login':None}
def outter(func): # func = 最原始的login函式的記憶體地址
def get_time(*args, **kwargs): # args = ('egon',) kwargs = {}
start = time.time()
res = func(*args, **kwargs) # 最原始的login函式的記憶體地址() 直接呼叫 func('egon')
end = time.time()
print('func run time:%s'%(end-start))
return res
return get_time
def login_auth2(data_source,x,t):
# data_source = 'file'
def login_auth(func):
# func = index
def inner(*args,**kwargs): # 這裡的引數是跟被裝飾函式的引數一一對應
if user_dic['is_login']:
res = func(*args, **kwargs)
return res
else:
if data_source == 'file':
username = input('please input your username>>>:').strip()
password = input('please input your password>>>:').strip()
if username == 'jason' and password == '123':
user_dic['is_login'] = True
res = func(*args,**kwargs)
return res
else:
print('username or password error')
elif data_source == 'MySQL':
print('from MySQL')
elif data_source == 'ldap':
print('ldap')
else:
print('暫無該資料來源')
return inner
return login_auth
# 裝飾器在裝飾的時候 順序從下往上
# 裝飾器在執行的時候 順序從上往下
# res = login_auth2('MySQL')
@login_auth2('file',1,2) # index = login_auth(get_time) index = inner函式的記憶體地址
# @login_auth
@outter # get_time = outter(index) index是最原始的index
def index():
time.sleep(1)
print('index')
return 'index'
index()