##閉包 :內部函數,在外部調用不在他函數範圍的變數 def outer(): x=10 def inner(): print(x) return inner #outer()() f=outer() f() 這裡inner就是一個閉包,閉包=內部函數+環境,這裡環境是x=10。閉包是為瞭解釋調用不 ...
##閉包 :內部函數,在外部調用不在他函數範圍的變數
def outer(): x=10 def inner(): print(x) return inner #outer()() f=outer() f()View Code
這裡inner就是一個閉包,閉包=內部函數+環境,這裡環境是x=10。
閉包是為瞭解釋調用不在他範圍的變數的現象
##裝飾器
1 import time 2 def show_runtime(func): 3 def inner(): 4 start_time=time.time() 5 time.sleep(1) 6 func() 7 end_time=time.time() 8 print(end_time-start_time) 9 return inner 10 11 def f(): 12 print('aiq') 13 14 f=show_runtime(f) #裝飾f函數 15 f()View Code
show_runtime()方法就是一個裝飾器
高大上的用法:
@show_runtime # 等於f=show_runtime(f),這樣已經裝飾了 def f(): print('aiq')
#裝飾器裡面的參數,在inner函數加參數,以及inner裡面的函數也要加參數
import time def show_runtime(func): def inner(*x,**y): start_time=time.time() func(*x,**y) end_time=time.time() print(end_time-start_time) return inner @show_runtime #等於f=show_runtime(f) def add(*a,**b): sum=0 for i in a: sum+=i print(sum) time.sleep(1) add(3,5,7)View Code
import time def logger(flag=False): def show_runtime(func): def inner(*x,**y): start_time=time.time() func(*x,**y) end_time=time.time() print(end_time-start_time) if flag==True: #如果標記是True則執行 pass return inner return show_runtime @logger(True) #等於先調用logger函數,然後在執行@show_time,這裡相當於閉包,調用外部的變數 def add(*a,**b): sum=0 for i in a: sum+=i print(sum) time.sleep(1) add(3,5,7)View Code
作業:
1 # __author: _nbloser 2 # date: 2017/12/25 3 # username, passwd = 'xia', 123 # 要在文件裡面的 4 def read_user_messege(file_name): 5 f = open(file_name) 6 data = eval(f.read()) 7 f.close() 8 return data 9 10 11 def logger(auth_type='jingdong'): 12 def decorator(func): 13 def inner(): 14 global status_login 15 if status_login == False: 16 username_input = input('input username:') 17 user_table = read_user_messege(''.join([auth_type, '.txt'])) 18 if username_input in user_table: 19 passwd_input = input('input passwd:') 20 if user_table[username_input] == passwd_input: 21 status_login = True 22 func() 23 else: 24 print('密碼錯誤,登錄失敗!') 25 else: 26 print('沒有該用戶') 27 if status_login == True: 28 func() 29 30 return inner 31 32 return decorator 33 34 35 @logger() 36 def home(): 37 print("welcome, home page.") 38 39 40 @logger('wechat') 41 def finance(): 42 print('finance.') 43 44 45 @logger() 46 def book(): 47 print('book') 48 49 50 status_login = False 51 while True: 52 print('1:home\n' 53 '2:finance\n' 54 '3:book\n' 55 'others:exit\n') 56 elect = input('>>>') 57 if elect == '1': 58 home() 59 elif elect == '2': 60 finance() 61 elif elect == '3': 62 book() 63 else: 64 breakView Code
jingdong.txt: {'xia': 'aiq', 'q': 'aix'}
wechat.txt:{'xia': 'wh_aiq', 'q': 'wh_aix'}
補充書中例子:因為這個沒有基礎,個人覺得多寫幾個熟悉。
1 # __author: _nbloser 2 # date: 2017/12/25 3 4 def foo(f): 5 """foo function Docstring""" 6 7 def wrapper(*x, **y): 8 """wrapper doc""" 9 print('調用函數:', f.__name__) 10 return f(*x, **y) 11 12 return wrapper 13 14 @foo 15 def bar(x): 16 return x**2 17 18 if __name__=='__main__': 19 print(bar(2)) 20 print(bar.__name__) 21 print(bar.__doc__)View Code
1 # __author: _nbloser 2 # date: 2017/12/25 3 4 def outter(func): 5 def inner(*x, **y): 6 print('aiq') 7 func(*x, **y) 8 9 return inner 10 11 12 @outter 13 def my_add(a, b): 14 print(a + b) 15 16 17 if __name__ == '__main__': 18 my_add(2, 8)View Code
1 # __author: _nbloser 2 # date: 2017/12/25 3 4 import time, functools 5 6 7 def timeit(func): 8 def wrapper(*args): 9 start = time.perf_counter() 10 func(*args) 11 end = time.perf_counter() 12 print('運行時間:', end - start) 13 14 return wrapper 15 16 17 @timeit 18 def my_sum(n): 19 sum = 0 20 for i in range(n): 21 sum += i 22 print(sum) 23 24 25 if __name__ == '__main__': 26 my_sum(10000)View Code
1 # __author: _nbloser 2 # date: 2017/12/25 3 4 import time 5 6 7 def outer(func): 8 def inner(*args): 9 start_time = time.time() 10 func(*args) 11 time.sleep(1) 12 end_time = time.time() 13 print('運行時間:', end_time - start_time) 14 15 return inner 16 17 18 @outer 19 def my_factorial(n): 20 product = 1 21 for i in range(2, n): 22 product *= i 23 print(product) 24 25 26 my_factorial(25)View Code
1 # __author: _nbloser 2 # date: 2017/12/25 3 def make_bold(func): 4 def wrapper(*args): 5 return ''.join(['<b>', func(*args), '<b/>']) 6 7 return wrapper 8 9 10 def make_italic(func): 11 def wrapper(*args): 12 return ''.join(['<i>', func(*args), '</i>']) 13 14 return wrapper 15 16 17 @make_bold 18 @make_italic 19 def html_tags(str1): 20 return str1 21 22 23 print(html_tags('hello')) 24 # 運行結果:<b><i>hello</i><b/>View Code