簡體   English   中英

python中'nonlocal'關鍵字的用法

[英]Usage of 'nonlocal' keyword in python

下面的程序詢問帶有UnboundLocalError: local variable 'balance' referenced before assignment nonlocal關鍵字UnboundLocalError: local variable 'balance' referenced before assignment

>>> def make_withdraw(balance):
    """Return a withdraw function with a starting balance."""
    def withdraw(amount):
        if amount > balance:
            return 'Insufficient funds'
        balance = balance - amount
        return balance
    return withdraw

>>> withdraw = make_withdraw(101)
>>> withdraw(25)

但是,當內部函數shift在賦值之前將lst引用為temp = lst[0]時,以下程序不會給出此類錯誤。

def shift_left(lst, n):
    """Shifts the lst over by n indices

    >>> lst = [1, 2, 3, 4, 5]
    >>> shift_left(lst, 2)
    >>> lst
    [3, 4, 5, 1, 2]
    """
    assert (n > 0), "n should be non-negative integer"
    def shift(ntimes):
        if ntimes == 0:
            return
        else:
            temp = lst[0]
            for index in range(len(lst) - 1):
                lst[index] = lst[index + 1]         
            lst[index + 1] = temp
            return shift(ntimes-1)
    return shift(n)

我如何理解/比較這兩種情況?

您永遠不會分配給lst ,而只會分配給lst[index] 這兩個概念並不完全相同。

該行:

lst = some_other_value

將重新綁定名稱lst指向另一個對象。 該行:

lst[index] = some_other_value

通過將序列中的特定索引綁定到其他對象來更改名稱lst引用的對象。 名稱lst本身從未更改,因此在此名稱所屬的范圍方面沒有任何歧義。

在Python作用域中,只有對名稱本身的綁定操作才算在內。 綁定操作不僅是(直接)賦值,還包括函數參數,函數和類定義, import語句和目標, except .. aswith .. as和目標in for ... in循環外。 如果在給定范圍內綁定了名稱,則將其視為本地名稱 ,在所有其他情況下,Python會在父范圍內查找名稱,最外層的范圍為global

在這種情況下,對訂閱的分配(使用[...] )不是綁定操作。

請參閱Python執行模型文檔的命名和綁定部分 ,以及作用域規則簡短說明? 帖子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM