Python初學者第二十三天 函數進階(2)裝飾器
阿新 • • 發佈:2018-01-31
分享 username 執行 ... ret 傳參 als print n)
23day
裝飾器:
1、用戶不執行前不調用函數,在調用的時候再執行函數
a、傳函數時不加參數
user_status = False # 用戶登錄了就把這個改成True def login(func): def inner(): _username = ‘alex‘ _password = ‘abc123‘ global user_status if user_status == False: username = input("user:") password = input("password:") if username == _username and password == _password: print("welcome login...") user_status = True else: print("wrong username or password!") if user_status: func() return inner @login def home1(): print("首頁1") @login #等值於 home2 = login(home2) def home2(): print("首頁2") @login def home3(): print("首頁3") home1() home2() home3()
b、傳函數時增加參數:
註:可以使用非固定函數*args、**kwargs。當傳參數給函數時,取參數。不給函數傳參數,則不取
1 user_status = False # 用戶登錄了就把這個改成True 2 def login(func): 3 def inner(*args,**kwargs): 4 _username = ‘alex‘ 5 _password = ‘abc123‘ 6 global user_status 7 if user_status == False: 8 username = input("user:") 9 password = input("password:") 10 if username == _username and password == _password: 11 print("welcome login...") 12 user_status = True 13 else: 14 print("wrong username or password!") 15 16 ifuser_status: 17 func(*args,**kwargs) 18 return inner 19 @login 20 def home1(): 21 print("首頁1") 22 # @login #等值於 home2 = login(home2) 23 def home2(n): 24 print("首頁2",n) 25 26 def home3(): 27 print("首頁3") 28 home1() 29 home2(‘3p‘) 30 home3()
c、帶參數的裝飾器
可在外函數與內函數之間再套一層過度函數
user_status = False # 用戶登錄了就把這個改成True def login(func): def outer(func): def inner(*args,**kwargs): _username = ‘alex‘ _password = ‘abc123‘ global user_status if user_status == False: username = input("user:") password = input("password:") if username == _username and password == _password: print("welcome login...") user_status = True else: print("wrong username or password!") if user_status: func(*args,**kwargs) return inner return outer @login(‘qq‘) #先執行login(‘qq‘) 再將login(‘qq‘)@到home1 def home1(): print("首頁1") # @login #等值於 home2 = login(home2) def home2(n): print("首頁2",n) def home3(): print("首頁3") home1() home2(‘3p‘) home3()
Python初學者第二十三天 函數進階(2)裝飾器