Python 中的 nonlocal 关键字: 理解嵌套函数变量修改
Python 中的 'nonlocal' 关键字是一种用于嵌套函数的声明,它告诉 Python 解释器在当前作用域中使用外层函数的变量 'count',而不是创建一个新的局部变量。
例如,在以下代码中,'count' 是在 'count_inversions' 函数中定义的变量。然而,在 'merge_sort' 和 'merge' 函数中,我们希望能够更新 'count' 变量的值。为了实现这个功能,我们使用了 'nonlocal count' 声明,以便在这两个函数中使用 'count' 变量,并且对它进行修改。
def count_inversions(arr):
count = 0
def merge_sort(arr):
nonlocal count
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
merge(left, right, arr)
merge_sort(arr)
return count
def merge(left, right, arr):
nonlocal count
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
count += len(left) - i
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
不使用 'nonlocal count' 声明的话,Python 解释器会将 'count' 视为 'merge_sort' 和 'merge' 函数中的局部变量,而不是外层函数中的变量。这样,在对 'count' 进行修改时,只会修改局部变量的值,而不会影响到外层函数中的变量。因此,为了正确地更新外层函数中的 'count' 变量,我们使用了 'nonlocal count' 声明。
'nonlocal' 关键字是 Python 中一个重要的概念,它允许我们在嵌套函数中修改外层函数的变量,从而实现更灵活的代码结构。
原文地址: https://www.cveoy.top/t/topic/bdkb 著作权归作者所有。请勿转载和采集!