English documents:
Locals ()
Update and return a dictionary representing the current local symbol table. Free variables was returned by locals () when it was called in function blocks, and not in class blocks.
Description
1. Function function returns a dictionary of local variables and their values in the current scope, similar to the GLOBALS function (returns a global variable)
>>> locals () {' __package__ ': None, ' __loader__ ':
, ' __doc__ ': None, ' __name__ ': ' __main__ ', ' __ Builtins__ ':
, ' __spec__ ': none}>>> a = 1>>> locals () # More than one key for a value of 1 {' __package__ ': None, ' __loader__ ':
, ' a ': 1, ' __doc__ ': None, ' __name__ ': ' __main__ ', ' __builtins__ ':
, ' _ _spec__ ': None}
2. Can be used in functions.
>>> def f (): print ( ' before define a ') print (Locals ()) #作用域内无变量 a = 1 print (' after define A ') print (Locals ()) #作用域内有一个a变量 with a value of 1 >>> f
>>> F () before define a {} after Define a{' a ': 1}
3. The returned dictionary collection cannot be modified.
>>> def f (): Print (' before define a ') print (Locals ()) # in scope no variable a = 1 print (' after define a ')
print (Locals ()) # has an A variable in the scope with a value of 1 b = locals () print (' b["a"]: ', b[' a ']) b[' a '] = 2 # Modify the b[' a '] value print ( ' Change locals value ') print (' b["a"]: ', b[' a ']) print (' A is ', a) # value unchanged >>> f () before define a {} After define a{' a ': 1}b["a"]: 1change locals valueb["A"]: 2a is 1>>>