Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python nonlocal

作者:淺墨   发布日期:2025-05-28   浏览:25

def outer_function():
    x = "local"

    def inner_function():
        nonlocal x  # 使用nonlocal关键字声明x是外部函数outer_function中的变量
        x = "nonlocal"
        print("inner:", x)

    inner_function()
    print("outer:", x)

outer_function()

解释说明:

  1. outer_function 定义了一个局部变量 x,其初始值为 "local"
  2. 在内部函数 inner_function 中,使用 nonlocal 关键字声明 x 是外部函数 outer_function 中的变量。
  3. 修改 x 的值为 "nonlocal" 并打印。
  4. 调用 inner_function 后,外部函数 outer_function 中的 x 也被修改为 "nonlocal" 并打印。

输出结果:

inner: nonlocal
outer: nonlocal

上一篇:python paramiko

下一篇:python print不换行

大家都在看

python时间格式

python ord和chr

python中的yield

python自定义异常

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站