废话不多说,直接代码啊~~~
a=999
b=99999
def test1():
a=888
b=88888
print(‘a={}‘.format(a))
print(‘b={}‘.format(b))
def test2():
global a
print(‘a={}‘.format(a))
a+=1
print(‘a={}‘.format(a))
nonlocal b
b+=1
print(‘b={}‘.format(b))
print(globals())
print(locals())
test2()
print(globals())
print(locals())
test1()
print(‘b={}‘.format(b))
print(globals())
print(locals())
输出结果:
a=888
b=88888
a=999
a=1000
b=88889
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x0000011762666FD0>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘H:/py/day12.py‘, ‘__cached__‘: None, ‘a‘: 1000, ‘b‘: 99999, ‘test1‘: <function test1 at 0x000001176261C1E0>}
{‘b‘: 88889}
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x0000011762666FD0>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘H:/py/day12.py‘, ‘__cached__‘: None, ‘a‘: 1000, ‘b‘: 99999, ‘test1‘: <function test1 at 0x000001176261C1E0>}
{‘a‘: 888, ‘test2‘: <function test1.<locals>.test2 at 0x000001176295A378>, ‘b‘: 88889}
b=99999
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x0000011762666FD0>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘H:/py/day12.py‘, ‘__cached__‘: None, ‘a‘: 1000, ‘b‘: 99999, ‘test1‘: <function test1 at 0x000001176261C1E0>}
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x0000011762666FD0>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘H:/py/day12.py‘, ‘__cached__‘: None, ‘a‘: 1000, ‘b‘: 99999, ‘test1‘: <function test1 at 0x000001176261C1E0>}
Process finished with exit code 0
原文:https://www.cnblogs.com/aqin1012/p/11330753.html