x=111
?
def func():
global x # 声明x这个名字是全局的名字,不要再造新的名字了
x=222
?
func()
print(x) # x--->222
可变类型一般不需要使用global
l=[111,222]
def func():
l.append(333)
?
func()
print(l)
修改函数外层函数包含的名字对应的值(不可变类型)
x=0
def f1():
x=11
def f2():
nonlocal x
x=22
f2()
print(‘f1内的x:‘,x) x--->22
?
f1()
可变类型不受控制:
def f1():
x=[]
def f2():
x.append(1111)
f2()
print(‘f1内的x:‘,x) x--->[1111]
?
f1()
原文:https://www.cnblogs.com/bailongcaptain/p/12547879.html