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()
解释说明:
outer_function
定义了一个局部变量 x
,其初始值为 "local"
。inner_function
中,使用 nonlocal
关键字声明 x
是外部函数 outer_function
中的变量。x
的值为 "nonlocal"
并打印。inner_function
后,外部函数 outer_function
中的 x
也被修改为 "nonlocal"
并打印。输出结果:
inner: nonlocal
outer: nonlocal
上一篇:python paramiko
下一篇:python print不换行
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站