1, locals () and Globals () are Python's built-in functions that provide a dictionary of ways to access local variables and global variables.
Example code:
1 defTest (ARG):2A=13b=24Data_dict = {}5 Printlocals ()6 PrintGlobals ()7 8 9 if __name__=='__main__':TenTest (3)
The output is:
1{'a': 1,'data_dict': {},'b': 2,'Arg': 3}2{'__builtins__': <module'__builtin__'(built-inch);'__file__':'f:/work/workspace/pythonworkspace/learn/locals_globals.py','__package__': None,'Test': <function test at 0x0239f830>'__name__':'__main__','__doc__': None}
2, locals () return is a deep copy of the current local variable, modify the value of the variable in locals (), in fact, there is no effect on the original variable itself. and Globals () returns a dictionary of global variables, modifies the contents, and the value is really changed.
Example code:
1b = 5#define a global variable2 deftest2 ():3A=14Locals () ["a"] = 2#modifying local variables5 Print "a=", a6Globals () ["b"] = 6#Modifying global variables7 Print "b=", b8 9 if __name__=='__main__':TenTest2 ()
The output is:
A= 1B= 6
Python in Locals () and Globals ()