1. 程式人生 > 實用技巧 >python區域性變數&全域性變數

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

區域性變數:

  在函式內優先呼叫區域性變數,沒找到區域性變數再呼叫全域性變數