eval 是干嘛的?
解析字符串表達式并執(zhí)行,并返回一個值
語法格式
1
|
eval (expression[, globals [, locals ]]) |
expression
:表達式字符串
globals
:必須是一個字典
locals
:可以是任何 map 對象
最簡單的表達式栗子
栗子一
1
2
3
4
5
6
7
8
9
|
print ( eval ( "123" )) print ( eval ( "True" )) print ( eval ( "(1,2,3)" )) print ( eval ( "[1,2,3]" )) # 輸出結果 123 True ( 1 , 2 , 3 ) [ 1 , 2 , 3 ] |
栗子二
1
2
3
4
5
6
|
print ( eval ( "1+2" )) x = 1 print ( eval ( 'x+1' )) # 輸出結果 3 2 |
栗子三
1
2
3
4
5
|
a = 1 b = 2 print ( eval ( "[a,b]" )) # 輸出結果 [ 1 , 2 ] |
帶上 globals
1
2
3
4
5
6
|
# 使用 globals x = 10 g = { "x" : 5 } print ( eval ( "x+1" , g)) # 輸出結果 6 |
在 eval 中提供了globals 參數(shù)
eval 的作用域就是 g 指定的這個字典,外面的 x = 10 被屏蔽掉了,eval 是看不見的,所以使用了 x 為 5 的值
1
2
3
4
5
6
7
8
9
|
x = 10 y = 5 g = { "x" : 5 } print ( eval ( "x+1+y" , g)) # 輸出結果 5 print ( eval ( "x+1+y" , g)) File "<string>" , line 1 , in <module> NameError: name 'y' is not defined |
因為 global 參數(shù)沒有 y 變量值,所以報錯了
帶上 locals
1
2
3
4
5
6
7
|
# 使用 locals a = 1 g = { "a" : 2 , "b" : 3 } l = { "b" : 30 , "c" : 4 } print ( eval ( "a+b+c" , g, l)) # 輸出結果 36 |
- eval 的作用域變成了 globals + locals
- locals 作用域優(yōu)先級會高于 globals
- locals 參數(shù)里面的值會覆蓋 globals 參數(shù)里面的值
字符串轉字典
1
2
3
4
5
|
# 字符串轉字典 jsons = "{'a':123,'b':True}" print(type(eval(jsons))) # 輸出結果 < class 'dict'> |
帶上 globals
1
2
3
|
print ( eval ( "{'name':'linux','age':age}" , { "age" : 123 })) # 輸出結果 { 'name' : 'linux' , 'age' : 123 } |
帶上 locals
1
2
3
|
print ( eval ( "{'name':'linux','age':age}" , { "age" : 123 }, { "age" : 24 })) # 輸出結果 { 'name' : 'linux' , 'age' : 24 } |
內(nèi)置函數(shù)栗子
1
2
3
4
5
6
7
|
# 內(nèi)置函數(shù) print ( eval ( "dir()" )) print ( eval ( "abs(-10)" )) # 輸出結果 [ '__annotations__' , '__builtins__' , '__cached__' , '__doc__' , '__file__' , '__loader__' , '__name__' , '__package__' , '__spec__' , 'a' , 'b' , 'g' , 'jsons' , 'l' , 'x' , 'y' ] 10 |
報錯的栗子
栗子一
1
2
3
4
5
|
print ( eval ( "aa" )) # 輸出結果 print ( eval ( "aa" )) File "<string>" , line 1 , in <module> NameError: name 'aa' is not defined |
栗子二
1
2
3
4
5
|
print ( eval ( "[a,b,c]" )) # 輸出結果 print ( eval ( "[a,b,c]" )) File "<string>" , line 1 , in <module> NameError: name 'c' is not defined |
栗子三
1
2
3
4
5
6
7
|
print ( eval ( "if x: print(x)" )) # 輸出結果 print ( eval ( "if x: print(x)" )) File "<string>" , line 1 if x: print (x) ^ SyntaxError: invalid syntax |
因為 eval() 只接受表達式任何其他語句(如if、for、while、import、def、class)都將引發(fā)錯誤
以上就是Python中eval函數(shù)的表達式用法示例的詳細內(nèi)容,更多關于Python中eval函數(shù)表達式的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/qq_33801641/article/details/120232630