一段代码分清global和nonlocal

Posted aqin1012

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一段代码分清global和nonlocal相关的知识,希望对你有一定的参考价值。

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

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的主要内容,如果未能解决你的问题,请参考以下文章

PHP检测每一段代码执行时间

PHP检测每一段代码执行时间

JavaSE之多线程

Python的函数参数传递 和 global

分清java中的接口和抽象类

php全局变量漏洞 $GLOBALS