人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動(dòng)態(tài)

總結(jié)分析Python的5個(gè)硬核函數(shù)

發(fā)布日期:2021-12-09 12:42 | 文章來源:源碼之家

對(duì)于想深入理解 Python 的朋友,很有必要認(rèn)真看看。喜歡本文點(diǎn)贊支持,歡迎收藏學(xué)習(xí)。

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 = 10
def func():
 y = 20
 a = 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ù)??梢岳斫鉃镻ython 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ù)試試:

x = 10
def func():
 y = 20
 a = 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 = 20
 exec(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)于:

x = 1
y = 2
def func():
 y = 3
 z = 4
 
 z = 30
 sum = x + y + z
 print(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 = 18
def 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 = 18
G = 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í)例:

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)存在(被定義)。

技術(shù)交流

歡迎轉(zhuǎn)載、收藏、有所收獲點(diǎn)贊支持一下!

到此這篇關(guān)于總結(jié)分析Python的5個(gè)硬核函數(shù)的文章就介紹到這了,更多相關(guān)Python 函數(shù)內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!

版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開通

自選配置、實(shí)時(shí)開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對(duì)1客戶咨詢顧問

在線
客服

在線客服:7*24小時(shí)在線

客服
熱線

400-630-3752
7*24小時(shí)客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部