1. 程式人生 >實用技巧 >其它 >60.Python之閉包

60.Python之閉包


  • 在一個巢狀函式內,外函式返回了內函式,且內函式使用了外函式中定義的區域性變數,這個就叫做閉包

例:

# 定義一個外函式
def outer():
    a = 1
    # 定義一個內函式
    def inner():
        # nonlocal關鍵字使外函式中定義的區域性變數可以在內函式中使用
        nonlocal a
        a += 1
        print(a)
    # 外函式返回內函式
    return inner

r = outer()  # 相當於:r = inner
r()  # 相當於:inner()
r()
r()

結果:

60.Python之閉包

總結:

  • 外函式中定義了局部變數,且內函式中會使用這個變數
  • 外函式中會返回內函式
  • 閉包的作用是:保護了局部變數,使區域性變數即可以使用,也不會被破壞

若何判斷一個函式是否是閉包函式,使用__closure__

# 定義一個外函式
def outer():
    a = 1
    # 定義一個內函式
    def inner():
        nonlocal a
        a += 1
        print(a)
    # 外函式返回內函式
    return inner

r = outer()  # 相當於:r = inner

# 判斷一個函式是否是閉包函式
# 返回cell表示是閉包函式,返回None表示不是閉包函式
print(r.__closure__)

60.Python之閉包