日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

Python中的eval,exec以及其相关函数

發(fā)布時(shí)間:2025/3/20 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python中的eval,exec以及其相关函数 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1. eval函數(shù)

函數(shù)的作用:

計(jì)算指定表達(dá)式的值。也就是說它要執(zhí)行的Python代碼只能是單個(gè)運(yùn)算表達(dá)式(注意eval不支持任意形式的賦值操作),而不能是復(fù)雜的代碼邏輯,這一點(diǎn)和lambda表達(dá)式比較相似。

函數(shù)定義:

eval(expression, globals=None, locals=None)

參數(shù)說明:

  • expression:必選參數(shù),可以是字符串,也可以是一個(gè)任意的code對(duì)象實(shí)例(可以通過compile函數(shù)創(chuàng)建)。如果它是一個(gè)字符串,它會(huì)被當(dāng)作一個(gè)(使用globals和locals參數(shù)作為全局和本地命名空間的)Python表達(dá)式進(jìn)行分析和解釋。

  • globals:可選參數(shù),表示全局命名空間(存放全局變量),如果被提供,則必須是一個(gè)字典對(duì)象。

  • locals:可選參數(shù),表示當(dāng)前局部命名空間(存放局部變量),如果被提供,可以是任何映射對(duì)象。如果該參數(shù)被忽略,那么它將會(huì)取與globals相同的值。

  • 如果globals與locals都被忽略,那么它們將取eval()函數(shù)被調(diào)用環(huán)境下的全局命名空間和局部命名空間。

返回值:

  • 如果expression是一個(gè)code對(duì)象,且創(chuàng)建該code對(duì)象時(shí),compile函數(shù)的mode參數(shù)是’exec’,那么eval()函數(shù)的返回值是None;
  • 否則,如果expression是一個(gè)輸出語(yǔ)句,如print(),則eval()返回結(jié)果為None;
  • 否則,expression表達(dá)式的結(jié)果就是eval()函數(shù)的返回值;

實(shí)例:

x = 10def func():y = 20a = eval('x + y')print('a: ', a)b = eval('x + y', {'x': 1, 'y': 2})print('b: ', b)c = eval('x + y', {'x': 1, 'y': 2}, {'y': 3, 'z': 4})print('c: ', c)d = eval('print(x, y)')print('d: ', d)func()

輸出結(jié)果:

a: 30 b: 3 c: 4 10 20 d: None

對(duì)輸出結(jié)果的解釋:

  • 對(duì)于變量a,eval函數(shù)的globals和locals參數(shù)都被忽略了,因此變量x和變量y都取得的是eval函數(shù)被調(diào)用環(huán)境下的作用域中的變量值,即:x = 10, y = 20,a = x + y = 30
  • 對(duì)于變量b,eval函數(shù)只提供了globals參數(shù)而忽略了locals參數(shù),因此locals會(huì)取globals參數(shù)的值,即:x = 1, y = 2,b = x + y = 3
  • 對(duì)于變量c,eval函數(shù)的globals參數(shù)和locals都被提供了,那么eval函數(shù)會(huì)先從全部作用域globals中找到變量x, 從局部作用域locals中找到變量y,即:x = 1, y = 3, c = x + y = 4
  • 對(duì)于變量d,因?yàn)閜rint()函數(shù)不是一個(gè)計(jì)算表達(dá)式,沒有計(jì)算結(jié)果,因此返回值為None

2. exec函數(shù)

函數(shù)的作用:

動(dòng)態(tài)執(zhí)行Python代碼。也就是說exec可以執(zhí)行復(fù)雜的Python代碼,而不像eval函數(shù)那么樣只能計(jì)算一個(gè)表達(dá)式的值。

函數(shù)定義:

exec(object[, globals[, locals]])

參數(shù)說明:

  • object:必選參數(shù),表示需要被指定的Python代碼。它必須是字符串或code對(duì)象。如果object是一個(gè)字符串,該字符串會(huì)先被解析為一組Python語(yǔ)句,然后在執(zhí)行(除非發(fā)生語(yǔ)法錯(cuò)誤)。如果object是一個(gè)code對(duì)象,那么它只是被簡(jiǎn)單的執(zhí)行。
  • globals:可選參數(shù),同eval函數(shù)
  • locals:可選參數(shù),同eval函數(shù)

返回值:

exec函數(shù)的返回值永遠(yuǎn)為None.

需要說明的是在Python 2中exec不是函數(shù),而是一個(gè)內(nèi)置語(yǔ)句(statement),但是Python 2中有一個(gè)execfile()函數(shù)。可以理解為Python 3把exec這個(gè)statement和execfile()函數(shù)的功能夠整合到一個(gè)新的exec()函數(shù)中去了:

  • eval()函數(shù)與exec()函數(shù)的區(qū)別:
  • eval()函數(shù)只能計(jì)算單個(gè)表達(dá)式的值,而exec()函數(shù)可以動(dòng)態(tài)運(yùn)行代碼段。
  • eval()函數(shù)可以有返回值,而exec()函數(shù)返回值永遠(yuǎn)為None。

實(shí)例1:

我們把實(shí)例1中的eval函數(shù)換成exec函數(shù)試試:

''' 遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書! ''' x = 10def func():y = 20a = exec('x + y')print('a: ', a)b = exec('x + y', {'x': 1, 'y': 2})print('b: ', b)c = exec('x + y', {'x': 1, 'y': 2}, {'y': 3, 'z': 4})print('c: ', c)d = exec('print(x, y)')print('d: ', d)func()

輸出結(jié)果:

a: None b: None c: None 10 20 d: None

因?yàn)槲覀冋f過了,exec函數(shù)的返回值永遠(yuǎn)為None。

實(shí)例2:

x = 10 expr = """ z = 30 sum = x + y + z print(sum) """ def func():y = 20exec(expr)exec(expr, {'x': 1, 'y': 2})exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})func()

輸出結(jié)果:

60 33 34

對(duì)輸出結(jié)果的解釋:

前兩個(gè)輸出跟上面解釋的eval函數(shù)執(zhí)行過程一樣,不做過多解釋。關(guān)于最后一個(gè)數(shù)字34,我們可以看出是:x = 1, y = 3是沒有疑問的。關(guān)于z為什么還是30而不是4,這其實(shí)也很簡(jiǎn)單,我們只需要在理一下代碼執(zhí)行過程就可以了,其執(zhí)行過程相當(dāng)于:

''' 遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書! ''' x = 1 y = 2def func():y = 3z = 4z = 30sum = x + y + zprint(sum)func()

3. globals()與locals()函數(shù)

函數(shù)定義及功能說明:

先來看下這兩個(gè)函數(shù)的定義和文檔描述

globals()

描述: Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

翻譯: 返回一個(gè)表示當(dāng)前全局標(biāo)識(shí)符表的字典。這永遠(yuǎn)是當(dāng)前模塊的字典(在一個(gè)函數(shù)或方法內(nèi)部,這是指定義該函數(shù)或方法的模塊,而不是調(diào)用該函數(shù)或方法的模塊)

locals()

描述: Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

Note The contents of this dictionary should not be modified; changes
may not affect the values of local and free variables used by the
interpreter.

翻譯: 更新并返回一個(gè)表示當(dāng)前局部標(biāo)識(shí)符表的字典。自由變量在函數(shù)內(nèi)部被調(diào)用時(shí),會(huì)被locals()函數(shù)返回;自由變量在類累不被調(diào)用時(shí),不會(huì)被locals()函數(shù)返回。

注意: locals()返回的字典的內(nèi)容不應(yīng)該被改變;如果一定要改變,不應(yīng)該影響被解釋器使用的局部變量和自由變量。

總結(jié):

  • globals()函數(shù)以字典的形式返回的定義該函數(shù)的模塊內(nèi)的全局作用域下的所有標(biāo)識(shí)符(變量、常量等)
  • locals()函數(shù)以字典的形式返回當(dāng)前函數(shù)內(nèi)的局域作用域下的所有標(biāo)識(shí)符
  • 如果直接在模塊中調(diào)用globals()和locals()函數(shù),它們的返回值是相同的

實(shí)例1:

name = 'Tom' age = 18def func(x, y):sum = x + y_G = globals()_L = locals()print(id(_G), type(_G), _G)print(id(_L), type(_L), _L)func(10, 20)

輸出結(jié)果:

2131520814344 <class 'dict'> {'__builtins__': <module 'builtins' (built-in)>, 'func': <function func at 0x000001F048C5E048>, '__doc__': None, '__file__': 'C:/Users/wader/PycharmProjects/LearnPython/day04/func5.py', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001F048BF4C50>, '__spec__': None, 'age': 18, '__name__': '__main__', 'name': 'Tom', '__package__': None, '__cached__': None} 2131524302408 <class 'dict'> {'y': 20, 'x': 10, '_G': {'__builtins__': <module 'builtins' (built-in)>, 'func': <function func at 0x000001F048C5E048>, '__doc__': None, '__file__': 'C:/Users/wader/PycharmProjects/LearnPython/day04/func5.py', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001F048BF4C50>, '__spec__': None, 'age': 18, '__name__': '__main__', 'name': 'Tom', '__package__': None, '__cached__': None}, 'sum': 30}

實(shí)例2:

name = 'Tom' age = 18G = globals() L = locals() print(id(G), type(G), G) print(id(L), type(L), L)

輸出結(jié)果:

2494347312392 <class 'dict'> {'__file__': 'C:/Users/wader/PycharmProjects/LearnPython/day04/func5.py', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000244C2E44C50>, 'name': 'Tom', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None, 'L': {...}, '__package__': None, '__name__': '__main__', 'G': {...}, '__doc__': None, 'age': 18} 2494347312392 <class 'dict'> {'__file__': 'C:/Users/wader/PycharmProjects/LearnPython/day04/func5.py', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000244C2E44C50>, 'name': 'Tom', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None, 'L': {...}, '__package__': None, '__name__': '__main__', 'G': {...}, '__doc__': None, 'age': 18}

上面打印出的G和L的內(nèi)存地址是一樣的,說明在模塊級(jí)別locals()的返回值和globals()的返回值是相同的。

4. compile函數(shù)

函數(shù)的作用:

將source編譯為code對(duì)象或AST對(duì)象。code對(duì)象能夠通過exec()函數(shù)來執(zhí)行或者通過eval()函數(shù)進(jìn)行計(jì)算求值。

函數(shù)定義:

compile(source, filename, mode[, flags[, dont_inherit]])

參數(shù)說明:

  • source:字符串或AST(Abstract Syntax Trees)對(duì)象,表示需要進(jìn)行編譯的Python代碼
  • filename:指定需要編譯的代碼文件名稱,如果不是從文件讀取代碼則傳遞一些可辨認(rèn)的值(通常是用’’)
  • mode:用于標(biāo)識(shí)必須當(dāng)做那類代碼來編譯;如果source是由一個(gè)代碼語(yǔ)句序列組成,則指定mode=‘exec’;如果source是由單個(gè)表達(dá)式組成,則指定mode=‘eval’;如果source是由一個(gè)單獨(dú)的交互式語(yǔ)句組成,則指定mode=‘single’。
  • 另外兩個(gè)可選參數(shù)暫不做介紹

實(shí)例:

''' 遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書! ''' s = """ for x in range(10):print(x, end='') print() """ code_exec = compile(s, '<string>', 'exec') code_eval = compile('10 + 20', '<string>', 'eval') code_single = compile('name = input("Input Your Name: ")', '<string>', 'single')a = exec(code_exec) b = eval(code_eval)c = exec(code_single) d = eval(code_single)print('a: ', a) print('b: ', b) print('c: ', c) print('name: ', name) print('d: ', d) print('name; ', name)

輸出結(jié)果:

0123456789 Input Your Name: Tom Input Your Name: Jerry a: None b: 30 c: None name: Jerry d: None name; Jerry

5. 這幾個(gè)函數(shù)的關(guān)系

comiple()函數(shù)、globals()函數(shù)、locals()函數(shù)的返回結(jié)果可以當(dāng)作eval()函數(shù)與exec()函數(shù)的參數(shù)使用。

另外,我們可以通過判斷globals()函數(shù)的返回值中是否包含某個(gè)key來判斷,某個(gè)全局變量是否已經(jīng)存在(被定義)。

總結(jié)

以上是生活随笔為你收集整理的Python中的eval,exec以及其相关函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。