英文文件:
locals()
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals()blonwhen it table. Free variables are returned by locals()blonwhen it it 片語 in function notmeat,not not f5555555555555p p.
說明: 1. 函數功能傳回目前作用域內的局部變數和其值組成的字典,與globals函數類似(傳回全域變數)>>> locals() {'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None} >>> a = 1 >>> locals() # 多了一个key为a值为1的项 {'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'a': 1, '__doc__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}
>>> def f(): print('before define a ') print(locals()) #作用域内无变量 a = 1 print('after define a') print(locals()) #作用域内有一个a变量,值为1 >>> f <function f at 0x03D40588> >>> f() before define a {} after define a {'a': 1}
>>> def f(): print('before define a ') print(locals()) # 作用域内无变量 a = 1 print('after define a') print(locals()) # 作用域内有一个a变量,值为1 b = locals() print('b["a"]: ',b['a']) b['a'] = 2 # 修改b['a']值 print('change locals value') print('b["a"]: ',b['a']) print('a is ',a) # a的值未变 >>> f() before define a {} after define a {'a': 1} b["a"]: 1 change locals value b["a"]: 2 a is 1 >>>