返回文章列表

Python nonlocal关键字

lyj

Python nonlocal关键字:围绕示例代码、详细解释、1. 外部函数 outer function、2. 内部函数 inner function等内容展开,整理关键步骤、配置方法、注意事项和常见问题,便于快速查阅与实践。

nonlocal 关键字在 Python 中用于在嵌套函数中引用外部非全局变量。这意味着可以在嵌套函数中修改外部函数的变量,而不是创建一个新的局部变量。

示例代码

下面是一个使用 nonlocal 的简单示例,帮助你理解它的作用和用法:

def outer_function():
    var = "Hello"
    
    def inner_function():
        nonlocal var  # 声明使用外部函数的变量,而不是创建新的局部变量
        var = "Hello, World!"
        print("Inner:", var)
    
    inner_function()
    print("Outer:", var)

outer_function()

详细解释

1. 外部函数 outer_function

```python
def outer_function():
	var = "Hello"
```

`outer_function` 定义了一个变量 `var` 并赋值为 "Hello"。

2. 内部函数 inner_function

```python
def inner_function():
	nonlocal var  # 声明使用外部函数的变量
	var = "Hello, World!"
	print("Inner:", var)

```

`inner_function` 是一个嵌套在 `outer_function` 内部的函数。在 `inner_function` 中,使用 `nonlocal var` 声明引用 `outer_function` 中的 `var` 变量。随后,修改 `var` 的值为 "Hello, World!",并打印出来。

3. 调用 inner_function

```python
inner_function()
```

在 `outer_function` 中调用 `inner_function`,此时 `inner_function` 会修改 `var` 的值。

4. 打印结果

```python
print("Outer:", var)
```

最后,打印 `outer_function` 中的 `var`,其值已经被 `inner_function` 修改为 "Hello, World!"。

### 输出结果

```python
Inner: Hello, World!
Outer: Hello, World!
```