共計 369 個字符,預計需要花費 1 分鐘才能閱讀完成。
在 Python 中,延遲綁定是指在閉包中使用外部變量時,變量的值在函數被調用時決定,而不是在函數定義時決定。要設置延遲綁定,可以使用 nonlocal
關鍵字。
下面是一個示例:
def outer_function():
x = 10
def inner_function():
nonlocal x
x += 1
print(x)
return inner_function
closure = outer_function()
closure() # 輸出 11
closure() # 輸出 12
在上面的例子中,outer_function
返回了一個閉包 inner_function
,在inner_function
中使用了 nonlocal
關鍵字來聲明 x
是外部函數 outer_function
中的變量。每次調用閉包 closure
時,x
的值會延遲綁定并自增 1。
丸趣 TV 網 – 提供最優質的資源集合!
正文完