Fifteen, python precipitation road -- the usage of eval()

1. The eval function

The function of the python eval() function: evaluate the string str as a valid expression and return the result of the calculation.

Syntax: eval(source[, globals[, locals]]) -> value

parameter:

source: a Python expression or the code object returned by the function compile()

globals: optional. must be dictionary

locals: optional. any map object

If the globals parameter is provided, it must be of type dictionary; if the locals parameter is provided, it can be any map object.

Python's global namespace is stored in a dict object called globals(); local namespaces are stored in a dict object called locals(). We can use print (locals()) to see all the variable names and variable values ​​in the body of the function.

 1 x = 1
 2 y = 1
 3 num = eval("x+y")
 4 print('num',num)
 5 
 6 def g():
 7     x = 2
 8     y = 2
 9     num1 = eval("x+y")
10     print('num1',num1)
11     num2 =eval("x+y",globals())
12     print('num2',num2)
13     num3 = eval("x+y",globals(),locals())
14     print('num3',num3)
15 
16 g()
1 num 2
 2 num1 4
 3 num2 2
 4 num3 4

Analysis: num2 is a global variable because it has globals, and the result after execution is 4; num3 has both globals and locals, only in this case, the value of locals is preferred, so the calculation result is 2

Second, eval can convert list, tuple, dict into str, and the return is also established; that is, mutual conversion.

1  # ############## 
2  # Convert the string to a 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  # Convert string to 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  # Convert the string to a tuple 
3 s = ' ([1,2,],(3 ,4,),[5,6,],(8,9)) ' 
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'>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325079441&siteId=291194637