簡單
def set_level(level):
def set_func(func):
def call_func(*args, **kwargs):
if level == 1:
print('--權限驗證級別爲1,驗證通過')
elif level == 5:
print('--權限驗證級別爲5,驗證通過')
return func()
return call_func
return set_func
# 只要裝飾器後面傳入了實參。就相當於執行了兩個步驟:
# 1.調用set_level函數並且將 1 當做實參傳遞
# 2.用上一步調用的返回值即: return set_func 返回了set_func的函數引用,當做裝飾器對test1函數進行裝飾
@set_level(1)
def test1():
'''執行該函數前需要驗證權限功能是否達到權限級別1'''
print('----test1----')
return 'OK'
@set_level(5)
def test2():
'''執行該函數前需要驗證權限功能是否達到權限級別5'''
print('---test2---')
return 'ok'
test1()
test2()