python局部变量&全局变量

全局变量:

  对于函数来讲,可以被引用,也可以“增删”(可变变量,列表、字典、集合),但不能被重新赋值:

name = {1,2,3,45}
def test():
    name.add(6)
    name.pop()
    print(globals())
    print(locals())
    print(name)
test()
#{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001FCE4B41910>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/pythondir/Day01/func.py', '__cached__': None, 'name': {2, 3, 6, 45}, 'test': <function test at 0x000001FCE4CF4040>}
#{}
#{2, 3, 6, 45}

  重新赋值(先调用,再重新赋值):

name = {1,2,3,45}
def test():
    name.add(6)
    name=6
    print(globals())
    print(locals())
    print(name)
test()
#Traceback (most recent call last):
  File "E:/pythondir/Day01/func.py", line 8, in <module>
    test()
  File "E:/pythondir/Day01/func.py", line 3, in test
    name.add(6)
UnboundLocalError: local variable 'name' referenced before assignment

局部变量:

  在函数内优先调用局部变量,没找到局部变量再调用全局变量

原文地址:https://www.cnblogs.com/thanos-ryan/p/13335295.html