1, locals () and Globals () are Python's built-in functions that provide a way to access local and global variables in the form of dictionaries.
def test (ARG):
a=1
b=2
data_dict = {}
print locals ()
print globals ()
if __name__ = ' __main__ ' :
Test (3)
Output:
{' A ': 1, ' data_dict ': {}, ' B ': 2, ' arg ': 3}
{' __builtins__ ': <module ' __builtin__ ' (built-in), ' __file__ ': ' f:/work/workspace/pythonworkspace/learn/ locals_globals.py ', ' __package__ ': None, ' Test ': <function test at 0x0239f830>, ' __name__ ': ' __main__ ', ' __doc__ ': None}
2, locals () return is the current local variable deep copy, modify locals () The value of the variable, in fact, the original variable itself is not any effect. The Globals () returns a dictionary of global variables, modifying the contents of which the value will actually change.
Sample code:
b = 5 # define a global variable
def test2 ():
a=1
locals () ["a"] = 2 # Modify local variable
print "A=", a
globals () ["B"] = 6 # Modify global variable
print "b=", b
if __name__ = = ' __main__ ':
test2 ()
The output is:
A= 1
b= 6