函數的內部函數,對外部做用域,而非全局做用域的引用。閉包
能夠打破層級關係,把局部變量拿到全局使用,而且能夠把外部的變量x封裝到f2中,而後下車直接調用f2就好了。app
x = 10 def f1(x): # f1()== f2 # x = 2 def f2(): print(x) return f2 # 把f2函數當作一個返回值返回給f1. f2 =f1(1) # f1()就至關於把f2的值拿到,而後在賦值給一個變量名爲f2。 f2() 1
全局中相同名字的變量不會影響局部的變量。ide
def f1(x): print(x) f1(1) 1
def f1(x): def f2(): print(x) return f2 f = f1(2) f() 2
返回的函數對象,不單單是一個函數對象,在該函數外還包裹一層做用域,這使得,該函數不管在何處調用,都優先使用本身外層包裹的做用域。函數
應用領域:延遲計算、爬蟲領域。url
import requests def outter(url): #outter() == spider ;spider() == response == requests.get(url) def spider(): # spider() == response response = requests.get(url) print(response.status_code) return response return spider baidu = outter('https://www.baidu.com') # baidu == spider baidu() 200
是爲被裝飾器對象添加額外功能。裝飾器本質上也是一個函數,只不過這個函數具備裝飾的功能。code
當咱們想新增功能,但又不想修改原方法的使用方法,這個時候就能夠使用裝飾器。對象
裝飾器的實現必須遵循兩大原則:作用域
import time def time_sleep(): time.sleep(1) print('from time_sleep') def deco(func): # deco()== wrapper ; func == time_sleep def wrapper(): start = time.time() res = func() end = time.time() print(end - start) return res return wrapper time_sleep = deco(time_sleep) #func == time_sleep ,括號裏的time_sleep纔是調用上面函數time_sleep,而前面的time_sleep只是咱們自定義的一個接收變量值的變量名。 time_sleep() # time_sleep() == wrapper() from time_sleep 1.000948429107666
import time def time_sleep(): time.sleep(1) return 'longzeluola' def deco(func): def wrapper(*args,**kwargs): start = time.time() res = func(*args,**kwargs) end = time.time() print(end - start) return res return wrapper ##wrapper() == res == func() time_sleep = deco(time_sleep) #wrapper res = time_sleep() # wrapper() print(res) 1.0001847743988037 longzeluola
import time def time_sleep(x): #給定義了一個形參 time.sleep(x) return 'longzeluola' def deco(func): def wrapper(*args,**kwargs): start = time.time() res = func(*args,**kwargs) end = time.time() print(end - start) return res return wrapper ##wrapper() == res == func() time_sleep = deco(time_sleep) #wrapper res = time_sleep(3) # wrapper() print(res) 3.00034236907959 longzeluola
def deco(func): def wrapper(*args,**kwargs): res = func(*args,**kwargs) return res return wrapper
import time @deco # @deco == time_sleep == deco(time_sleep) def time_sleep(x): time.sleep(x) return 'longzeluola' time_sleep(5) 5.000701427459717