Python非本地语句Python是什么nonlocal语句do(在Python3.0及更高版本中)?官方Python网站上没有文档help("nonlocal")也不起作用。
3 回答

qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
nonlocal
:
x = 0def 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 = 0def 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 = 0def 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

慕码人8056858
TA贡献1803条经验 获得超6个赞
global
def make_counter(): count = 0 def counter(): nonlocal count count += 1 return count return counter
def counter_generator(): count = 0 while True: count += 1 yield count
但
添加回答
举报
0/150
提交
取消