感謝alex http://www.cnblogs.com/alex3714/articles/5765046.htmlhtml
import time def timer(func): """計算一個方法運行的時間""" def deco(): start_time = time.time() func() stop_time = time.time() print("the func run time is %s" % (stop_time - start_time)) return deco @timer def test(): time.sleep(3) print("in the test func") test()
#_*_coding:utf-8_*_ user_status = False #用戶登陸了就把這個改爲True def login(func): #把要執行的模塊從這裏傳進來 def inner():#再定義一層函數 _username = "alex" #僞裝這是DB裏存的用戶信息 _password = "abc!23" #僞裝這是DB裏存的用戶信息 global user_status if user_status == False: username = input("user:") password = input("pasword:") if username == _username and password == _password: print("welcome login....") user_status = True else: print("wrong username or password!") if user_status == True: func() # 看這裏看這裏,只要驗證經過了,就調用相應功能 return inner #用戶調用login時,只會返回inner的內存地址,下次再調用時加上()纔會執行inner函數 @login def america(): print("----歐美專區----") def japan(): print("----日韓專區----")
#_*_coding:utf-8_*_ user_status = False #用戶登陸了就把這個改爲True def login(auth_type): #把要執行的模塊從這裏傳進來 def auth(func): def inner(*args,**kwargs):#再定義一層函數 if auth_type == "qq": _username = "alex" #僞裝這是DB裏存的用戶信息 _password = "abc!23" #僞裝這是DB裏存的用戶信息 global user_status if user_status == False: username = input("user:") password = input("pasword:") if username == _username and password == _password: print("welcome login....") user_status = True else: print("wrong username or password!") if user_status == True: return func(*args,**kwargs) # 看這裏看這裏,只要驗證經過了,就調用相應功能 else: print("only support qq ") return inner #用戶調用login時,只會返回inner的內存地址,下次再調用時加上()纔會執行inner函數 return auth def home(): print("---首頁----") @login('qq') def america(): print("----歐美專區----") def japan(): print("----日韓專區----") @login('weibo') def other(style): ''' :param style: 喜歡看什麼類型的,就傳進來 :return: ''' print("----其餘專區----") home() # america = login(america) #你在這裏至關於把america這個函數替換了 # 那用戶調用時依然寫 america() # other("3p")