我希望foo内的变量发生变化,因为我在方法栏中使用了nonlocal关键字。我的理解是变量a,b,c不再是bar中的局部变量,它们只是foo中变量a,b,c的赋值,因此值应该在foo中更改。 我在python3中运行以下代码时没有看到这种情况。想知道我在想什么
下面是输出
From foo
a = 10
b = 20
c = 30
From bar
a = 11
b = 12
c = 19
From chu
a = 200
b = 300
c = 500
这是代码
def foo():
a = 10
b = 20
c = 30
print("From {func}\na = {a}\nb = {b}\nc = {c}\n".format(func="foo", a=a, b=b, c=c))
def bar():
nonlocal a
nonlocal b
nonlocal c
a = 11
b = 12
c = 19
print("From {func}\na = {a}\nb = {b}\nc = {c}\n".format(func="bar", a=a, b=b, c=c))
def chu():
a = 200
b = 300
c = 500
print("From {func}\na = {a}\nb = {b}\nc = {c}\n".format(func="chu",a=a,b=b,c=c))
chu()
bar()
foo()