码迷,mamicode.com
首页 > 其他好文 > 详细

一段代码分清global和nonlocal

时间:2019-08-10 11:28:40      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:UNC   glob   print   global   int   div   not   extern   pack   

废话不多说,直接代码啊~~~

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

 

一段代码分清global和nonlocal

标签:UNC   glob   print   global   int   div   not   extern   pack   

原文地址:https://www.cnblogs.com/aqin1012/p/11330753.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!