React Lazy 和 Suspense
阿新 • • 發佈:2022-04-15
閉包
什麼是閉包?
在一個函式當中,又定義了一個函式,並且裡面的函式使用了外面函式的引數,那麼這個整體就是一個閉包。
def test(): print("---1---") print(test) """ 表示的是記憶體當中的函式塊,是個記憶體地址 輸出結果: <function test at 0x00000286581EF160> """ test() """ 表示呼叫了test函式 輸出結果:---1--- """ b = test """ b也指向了該函式的記憶體地址 """ b() """ 通過函式塊賦值後的變數名,呼叫test函式 輸出結果:---1--- """
閉包
# 閉包
def test1(number):
print("---1---")
def test_in():
print("---2---")
print(number+100)
print("---3---")
return test_in
a = test1(100)
print(a)
"""
輸出結果:
---1---
---3---
<function test1.<locals>.test_in at 0x000002DCDD63FCA0>
"""
a = test1(100) # 此時 a 指向test_in函式 a() """ 輸出結果: ---1--- ---3--- ---2--- 200 """
什麼時候能用到閉包呢?
外面的函式給定了基礎條件,裡面的函式基於原來的基礎之上進行進一步的處理;
在裝飾品當中運用到,是裝飾品的原理;
b = test1(200) # 此時 b 指向test_in函式
b()
"""
輸出結果:
---1---
---3---
---2---
300
"""
閉包的應用
def w1(func): def inner(): print("許可權認證中···") func() # ---> 即呼叫了f1() return inner def f1(): print("f1") def f2(): print("f2") f1 = w1(f1) print(f1) # 指向 inner 函式的記憶體地址 # 輸出結果:<function w1.<locals>.inner at 0x000001681795FF70> f1() """ 輸出結果: 許可權認證中··· f1 """ f2 = w1(f2) f2() """ 輸出結果: 許可權認證中··· f2 """