One, the Eval function
The function of the Python eval () function: evaluates the string str as a valid expression and returns the result of the calculation.
Syntax: eval (source[, globals[, locals]), value
Parameters:
Source: The code object returned by a Python expression or function compile ()
Globals: Optional. It must be dictionary.
Locals: Optional. Arbitrary map Object
If the globals parameter is provided, it must be a dictionary type, or it can be an arbitrary map object if the locals parameter is provided.
The global namespace of Python is stored in a Dict object called Globals (), and the local namespace is stored in a Dict object called locals (). We can use print (locals ()) to view all variable names and variable values in the function body.
1x = 12y = 13num = eval ("X+y")4 Print('Num', num)5 6 defg ():7x = 28y = 29NUM1 = eval ("X+y")Ten Print('NUM1', NUM1) OneNum2 =eval ("X+y", Globals ()) A Print('num2', num2) -num3 = eval ("X+y", Globals (), locals ()) - Print('num3', num3) the -G ()
1 num 22 num1 43 num2 24 num3 4
Parsing: num2 Because there is globals so is a global variable, after the result is 4;num3 both globals and locals, only in this case, priority to use the value of locals, so the result is 2
Second, the Eval can convert list, tuple, dict to STR, return to also set up;
1 # ### ########### 2 # string into list 3 s = " [[1,2,],[3,4,],[5,6,],[8,9]] " 4 li = eval (s) 5 print (li 6 print (type (s)) 7 print (Type (LI))
1 [[1, 2], [3, 4], [5, 6], [8, 9]] 2 <class str " > 3 <class " list ;
1 # ### #################### 2 # string into dictionary 3 s = {1: ' A ', 2: ' B '} " 4 dic = eval (s) 5 print (DIC) 6 print (type (s)) 7 print (Type (DIC))
1 {1: " a , 2: " b " } 2 <class " str " >3 < class " dict ;
1 # ### ####################### 2 # string to tuple 3 s = ([Up,], (3,4,), [5,6,], (8,9)) " Span style= "COLOR: #008080" >4 tu = eval (s) 5 print (TU) 6 print ( Type (s)) 7 print (Type (TU))
1 ([1, 2], (3, 4), [5, 6], (8, 9))2 <class'str'> 3 <class'tuple'>
The use of--eval (), the path of the Python precipitation