#1、編寫裝飾器,爲函數加上認證的功能
def decorator(func):
def inner(*args, **kwargs):
name = input('用戶名:').strip()
password = input('密碼:')
if name == 'Noiccy' and password == '111111':
print('認證通過!')
func()
else:
print('認證失敗!')
return inner
@decorator
def show():
print('Welcome to Python!')
show()
#2、編寫裝飾器,在每次執行被裝飾函數之前讓用戶輸入用戶名,密碼,給用戶三次機會,登錄成功之後,才能訪問該函數.
def decorator(func):
def inner(*args, **kwargs):
num = 3
while num:
name = input('用戶名:').strip()
password = input('密碼:')
if name == 'Noiccy' and password == '111111':
print('登錄成功!')
func()
break
else:
if num != 1:
print('用戶名或密碼錯誤,請重新輸入(還有{}次機會)!'.format(num-1))
num -= 1
if num == 0:
print('登錄失敗!')
return inner
@decorator
def show():
print('Welcome to Python!')
show()
#3、隨便寫一個單層裝飾器和多層裝飾器,並將程序的執行過程用文字寫下來
def decorator(func):
def inner(*args, **kwargs):
print('----')
func(*args, **kwargs)
return inner
@decorator
def show():
print('哈哈')
show()
# @decorator等價於show = decorator(show),將show函數傳入decorator函數,返回inner函數,並將inner函數賦值給參數show,show = inner,
# 然後調用show函數,其實是調用decorator函數中的inner函數,執行print('----'), 然後調用func函數,即原來聲明的show函數
def decorator2(char):
def decorator1(func):
def inner(*args, **kwargs):
print(char*4)
func(*args, **kwargs)
return inner
return decorator1
@decorator2('*')
def show1():
print('哈哈')
show1()
#4、函數練習,檢查獲取傳入列表或元組對象的所有奇數位索引對應的元素,並將其作爲新列表返回給調用者。