Python compile() 函數(shù)

2019-03-16 10:45 更新

Python compile() 函數(shù)

Python 內(nèi)置函數(shù) Python 內(nèi)置函數(shù)

描述

Python compile() 函數(shù)將一個(gè)字符串編譯為字節(jié)代碼。

語(yǔ)法

以下是 compile() 方法的語(yǔ)法:

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

參數(shù)

  • source:字符串或者AST(Abstract Syntax Trees)對(duì)象。。
  • filename:代碼文件名稱(chēng),如果不是從文件讀取代碼則傳遞一些可辨認(rèn)的值。
  • mode:指定編譯代碼的種類(lèi)??梢灾付?exec, eval, single。
  • flags:變量作用域,局部命名空間,如果被提供,可以是任何映射對(duì)象。。
  • flags和dont_inherit是用來(lái)控制編譯源碼時(shí)的標(biāo)志

返回值

返回表達(dá)式執(zhí)行結(jié)果。

實(shí)例

以下展示了使用 compile 函數(shù)的實(shí)例:

>>>str = "for i in range(0,10): print(i)"
>>> c = compile(str,'','exec') # 編譯為字節(jié)代碼對(duì)象 
>>> c
<code object <module> at 0x10141e0b0, file "", line 1>
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17

Python 內(nèi)置函數(shù) Python 內(nèi)置函數(shù)

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)