Python非本地语句

Python nonlocal语句有什么作用(在Python 3.0及更高版本中)?

官方Python网站上没有文档,help("nonlocal")也无法使用。

回答:

比较一下,不使用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,其中inner()x是现在还outer()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非本地语句 的全部内容, 来源链接: utcz.com/qa/420929.html

回到顶部