Python非本地语句 [英] Python nonlocal statement
本文介绍了Python非本地语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python nonlocal
语句做什么(在Python 3.0及更高版本中)?
What does the Python nonlocal
statement do (in Python 3.0 and later)?
官方Python网站上没有文档, help(nonlocal)
/ p>
There's no documentation on the official Python website and help("nonlocal")
does not work, either.
推荐答案
比较,不使用 nonlocal
:
x = 0
def outer():
x = 1
def inner():
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 2
# outer: 1
# global: 0
使用 nonlocal
c> inner()' x
现在也是 outer()
code> x :
To this, using nonlocal
, where inner()
's x
is now also outer()
's x
:
x = 0
def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 2
# outer: 2
# global: 0
如果我们使用
global
,它会将x
全局值:
x = 0
def outer():
x = 1
def inner():
global x
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
# inner: 2
# outer: 1
# global: 2
这篇关于Python非本地语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文