# 帶參數的裝飾器 # 準備好qq文件用於保存qq密碼,tiktok用於保存抖音密碼 def get_dic(file_name): #獲取密碼庫 dic = {} with open(file_name,mode='r',encoding='utf-8') as f1: for line in f1: username,psw = line.strip().split('|') dic[username] = psw return dic def login(dic): # 3次登陸功能 time = 3 while time > 0: username = input('請輸入用戶名').strip() psw = input('請輸入密碼').strip() if dic.get(username)==psw: return True time -= 1 return False def wrapper_out(file_name): #裝飾器本體 def wrapper(func): #func=qq def inner(): dic = get_dic(file_name) # 獲取相應的密碼庫 if login(dic): #調用登錄函數 ret = func() return ret return False return inner return wrapper @wrapper_out('騰訊') # 1 , wrapper_out('騰訊')---> wrapper 2 , qq = wrapper(qq) => inner def qq(): print('歡迎登陸qq') return '登陸成功' print(qq()) # inner() @wrapper_out('tiktok') def tiktok(): print('歡迎訪問抖音') return '登陸成功' print(tiktok())
# 多個裝飾器裝飾同一個函數的運行順序 def w1(func): # func = 原函數text def inner(): print('正在運行w1.inner....1') #2 func() # 原函數text #3 print('正在運行w1.inner...2') #4 return inner def w2(func): # func == w1.inner def inner(): print('正在運行w2.inner...1') #1 func() print('正在運行w2.inner...2') #5 return inner @w2 # text = w2(text) 後面的text是w1.inner,前面的text == w2.inner @w1 # 先運行 text = w1(text) 後面的text是原函數,前面的text == w1.inner def text(): print('正在運行被裝飾的函數...') text()
函數或其餘代碼均可解決遞歸解決的問題,但遞歸在某些時候能有出奇制勝的效果python
本身調用本身app
def func(n): print('in func') n += 1 print(n) func(n) func(0) 官網規定:遞歸默認的最大深度是1000次 若是遞歸超過100次尚未解決這個問題,那麼執意用遞歸,效率很低 import sys sys.setrecursionlimit(10000000) # 設定遞歸最大次數
# 例一 # def age(n): # if n == 1: # return 18 # else: # return age(n - 1) + 2 # print(age(4)) # ''' # n = 4 age(3) + 2 # n = 3 age(2) + 2 # n = 2 age(1) + 2 # n = 1 18 # ''' # # 例二 # l1 = [1, 3, 5, ['小馬', '小劉', 18, [33, 44, [55, 77]]], [99, 22, 11, 9], 21] # # def func(lst): # for el in lst: # if type(el) != list: # print(el) # else: # func(el) # func(l1)