裝飾器前戲ide
import time def bar(): time.sleep(3) # 睡3秒 print("in the bar") def test1(func): print("in the test1") return func bar=test1(bar) # 把bar函數的內存地址傳給test1函數(func參數接受bar內存地址),test1函數再returne返回內存地址,再賦值給bar變量 bar()# bar變量(內存地址)加()就成了函數運行
裝飾器小高潮
函數
未加裝飾器前代碼code
def test1(): time.sleep(3) #睡3秒 print("in the test1") def test2(): time.sleep(3) print("in the test2") test1() test2()
加上裝飾器後內存
import time def timer(func): def deco(): start_time = time.time() # 獲取當前系統時間 (內容開始時間) func() stop_time = time.time() # 獲取當前系統時間 (內容結束時間) print("運行時間爲:%s"%(stop_time-start_time)) return deco @timer # @timer = test1=timer(test1) def test1(): time.sleep(3) #睡3秒 print("in the test1") @timer def test2(): time.sleep(3) print("in the test2") test1() test2()
裝飾器高潮
input
user,password = "lt","111" def login(login_type): print("login:",login_type) def user_login(func): def loging(*ages, **kwargs): print("*ages, **kwargs:", *ages, **kwargs) if login_type =="local": Username = input("用戶名:") Password = input("密碼:") if user == Username and password == Password: print("登錄成功!") return func(*ages, **kwargs) else: print("登錄失敗!") elif login_type == "ldap": print("我是ldap") return loging return user_login def index(): print("這裏是首頁index") @login(login_type="local") def home(name): print("這裏是我的頁home",name) return "我是返回的數據" @login(login_type="ldap") def bbs(): print("這裏是論壇頁bbs") index() print(home(user)) bbs()