Python?eval()?函數(shù)看這一篇就夠了
一、語法和參數(shù)
在Python中evel()函數(shù)的語法格式為eval(expression, globals=None, locals=None),注意后面還有g(shù)lobals參數(shù)和locals參數(shù)。eval()函數(shù)用于執(zhí)行一個(gè)字符串表達(dá)式,并且返回該表達(dá)式的值。與eval相近的有exec函數(shù),該函數(shù)將會(huì)在另一篇文章詳細(xì)講解。
- expression:表達(dá)式,上面提到evel函數(shù)用于執(zhí)行一個(gè)字符串表達(dá)式,表達(dá)式的內(nèi)容就放在此處。當(dāng)表達(dá)式涉及到
- globals:該部分必須是字典!必須是字典!必須是字典!否則程序會(huì)出錯(cuò)。當(dāng)定義了globals 參數(shù)之后eval函數(shù)的作用域會(huì)被限定在globals中。
- locals:該參數(shù)掌控局部的命名空間,功能和globals類型,不過當(dāng)參數(shù)沖突時(shí),會(huì)執(zhí)行l(wèi)ocals處的參數(shù)。
二、expression參數(shù)示例
a=10;
print(eval("a+1"))
運(yùn)行結(jié)果為11
【解析】:因?yàn)榇颂帥]有指定globals和locals,所以直接執(zhí)行expression部分的內(nèi)容。該程序的效果等價(jià)于a=10 print(a+1)
三、globals參數(shù)示例
a=10;
g={'a':4}
print(eval("a+1",g))
運(yùn)行結(jié)果為5
【解析】:因?yàn)楝F(xiàn)在指定了globals,所以在expression部分的作用域就是globals指定的字典范圍內(nèi)。所以此時(shí)外面的a=10被屏蔽,取用字典中的值。
四、locals參數(shù)示例
a=10
b=20
c=30
g={'a':6,'b':8}
t={'b':100,'c':10}
print(eval('a+b+c',g,t))
運(yùn)行結(jié)果為116
【解析】:根據(jù)上面題目的練習(xí)我們知道了當(dāng)有g(shù)lobals和locals時(shí)作用的范圍域是在globals和locals中,所以a=10,b=20,c=30不會(huì)被應(yīng)用。a和c的值分別去字典g和字典t中的值,當(dāng)globals和locals中都有參數(shù)b時(shí)取locals中的值。所以a=6,b=100,c=10
五、eval函數(shù)的危險(xiǎn)之處
eval函數(shù)非常的方便,我們可以使用一行代碼就實(shí)現(xiàn)計(jì)算器的功能print(eval(input('請輸入')))。但是因?yàn)樗哂锌梢詫⒆址D(zhuǎn)成表達(dá)式執(zhí)行的特性,所以它也就可以去執(zhí)行系統(tǒng)命令。這樣很容易被別有用心的人用來執(zhí)行系統(tǒng)命令,刪除關(guān)鍵系統(tǒng)文件。
六、eval()函數(shù)官方文檔
The arguments are a string and optional globals and locals. If provided, globals must be a
dictionary. If provided, locals can be any mapping object.
The expression argument is parsed and evaluated as a Python expression (technically speaking,
a condition list) using the globals and locals dictionaries as global and local namespace. If the
globals dictionary is present and lacks ‘__builtins__', the current globals are copied into
globals before expression is parsed. This means that expression normally has full access to the
standard builtins module and restricted environments are propagated. If the locals dictionary is
omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression
is executed in the environment where eval() is called. The return value is the result of the
evaluated expression. Syntax errors are reported as exceptions. Example:
>>> x = 1
>>> eval('x+1')
2
This function can also be used to execute arbitrary code objects (such as those created by
compile()). In this case pass a code object instead of a string. If the code object has been
compiled with 'exec' as the mode argument, eval()‘s return value will be None.
Hints: dynamic execution of statements is supported by the exec() function. The globals() and
locals() functions returns the current global and local dictionary, respectively, which may be
useful to pass around for use by eval() or exec().
See ast.literal_eval() for a function that can safely evaluate strings with expressions
containing only literals.
附eval()函數(shù)常見作用有
1、計(jì)算字符串中有效的表達(dá)式,并返回結(jié)果
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> eval("n + 4")
85
2、將字符串轉(zhuǎn)成相應(yīng)的對象(如list、tuple、dict和string之間的轉(zhuǎn)換)
>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> b = eval(a)
>>> b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> a = "{1:'xx',2:'yy'}"
>>> c = eval(a)
>>> c
{1: 'xx', 2: 'yy'}
>>> a = "(1,2,3,4)"
>>> d = eval(a)
>>> d
(1, 2, 3, 4)
3、將利用反引號轉(zhuǎn)換的字符串再反轉(zhuǎn)回對象
>>> list1 = [1,2,3,4,5] >>> `list1` '[1, 2, 3, 4, 5]' >>> type(`list1`) <type 'str'> >>> type(eval(`list1`)) <type 'list'> >>> a = eval(`list1`) >>> a [1, 2, 3, 4, 5]
總結(jié)
到此這篇關(guān)于Python eval() 函數(shù)的文章就介紹到這了,更多相關(guān)Python eval() 函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python圖像處理之識別圖像中的文字(實(shí)例講解)
今天小編就為大家分享一篇Python圖像處理之識別圖像中的文字(實(shí)例講解),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
Pytorch實(shí)現(xiàn)List?Tensor轉(zhuǎn)Tensor,reshape拼接等操作
這篇文章主要介紹了Pytorch實(shí)現(xiàn)List?Tensor轉(zhuǎn)Tensor,reshape拼接等操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
基于Python實(shí)現(xiàn)成語填空游戲的示例代碼
成語填空想必大家都是十分熟悉的了,特別是有在上小學(xué)的家長肯定都有十分深刻的印象。當(dāng)然了你也別小看了成語調(diào)控小游戲,有的時(shí)候知識儲(chǔ)備不夠,你還真的不一定猜得出來是什么。本文就來用Python編寫一個(gè)簡單的成語填空游戲,感興趣的可以了解下2023-02-02
Python中os.path模塊的8個(gè)神奇函數(shù)分享
在Python編程中,os.path模塊是一個(gè)非常重要的模塊,它提供了用于處理文件路徑和目錄的函數(shù),本文將介紹os.path模塊中最常用的8個(gè)內(nèi)置函數(shù),需要的可以參考下2023-11-11
python requests爬取高德地圖數(shù)據(jù)的實(shí)例
今天小編就為大家分享一篇python requests爬取高德地圖數(shù)據(jù)的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11

