Python nonlocal 关键字
示例
在函数内部创建一个函数,该函数使用变量 x 作为非局部变量
def myfunc1()
x = "John"
def myfunc2()
nonlocal x
x = "hello"
myfunc2()
return x
print(myfunc1())
自己动手试一试 »
定义和用法
nonlocal
关键字用于处理嵌套函数内部的变量,其中变量不应属于内部函数。
使用关键字 nonlocal
来声明变量不是局部变量。
更多示例
示例
与上面相同的例子,但是没有 nonlocal 关键字
def myfunc1()
x = "John"
def myfunc2()
x = "hello"
myfunc2()
return x
print(myfunc1())
自己动手试一试 »
相关页面
关键字 global
用于创建全局变量。