2.关键字global,nonlocal
count=0
def func():
print(count)
count+=1
func()
UnboundLocalError: local variable 'count' referenced before assignment
解释器认为:如果你在局部作用域对一个变量进行修改了,
你在局部作用域已经定义好这个变量了。
global
-
可以在局部作用域声明一个全局变量。
这是剪切
def func(): global name name=1 print(globals()) # print(locals()) name+=1 print(globals()) func() print(name) print(globals()) ''' {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000002B0802C160>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': ''__cached__': None, 'func': <function func at 0x0000002B07F71E18>, 'name': 1} {} {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000002B0802C160>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '__cached__': None, 'func': <function func at 0x0000002B07F71E18>, 'name': 2} 2 {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000002B0802C160>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '__cached__': None, 'func': <function func at 0x0000002B07F71E18>, 'name': 2} '''
-
可以修改全局变量。
count=0 def func(): global count count +=1 print(count) func() print(count) ''' 0 1 '''
nonlocal是复制
nonlocal 不能操作全局变量
nonlocal 可以对父级作用域的变量进行修改,并且在当前作用域创建(复制)一份此变量。
def func():
count=0
def inner():
nonlocal count
count +=1
print(count)
print(locals()){'count': 1}
inner()
print(locals())#{'inner': <function func.<locals>.inner at 0x00000088E186AAE8>, 'count': 1}
func()
'''
1
{'count': 1}
{'inner': <function func.<locals>.inner at 0x00000088E186AAE8>, 'count': 1}
'''
UnboundLocalError: local variable 'count' referenced before assignment
解释器认为:如果你在局部作用域对一个变量进行修改了,
你在局部作用域已经定义好这个变量了。