compile() 方法从源对象计算 Python 代码并返回它。
示例
codeInString = 'a = 8\nb=7\nsum=a+b\nprint("sum =",sum)'
codeObject = compile(codeInString, 'sumstring', 'exec')
exec(codeObject)
# Output: 15
compile() 语法
compile() 的语法是
compile(source, filename, mode)
compile() 参数
compile() 方法接受以下参数:
source- 普通字符串、字节字符串或 AST 对象filename- 代码读取来源的文件mode-exec(可以接受包含语句、类和函数的代码块)、eval(接受单个表达式)或single(具有单个交互式语句)
注意: compile() 方法还有其他可选参数,如 flags、dont_inherit 和 optimize,但通常我们不使用它们。
compile() 返回值
compile() 方法返回
- 一个 Python 对象代码
示例:Python compile()
codeInString = 'a = 5\nb=6\nmul=a*b\nprint("mul =",mul)'
codeObject = compile(codeInString, 'multiplyNumbers', 'exec')
exec(codeObject)
# Output: mul = 30
在上面的示例中,source 参数是字符串变量 codeInString,它包含 Python 对象代码。
'a = 5\nb=6\nmul=a*b\nprint("mul =",mul)'
我们有一个编译方法来编译源
compile(codeInString, 'sumstring', 'exec')
其中,
filename是sumstringmode是exec- 传入的变量是
codeInString
我们将 compile() 方法在 exec 模式下赋值给 codeObject 变量。
exec() 方法执行 codeObject 变量并返回生成的 Python 对象。
另请阅读
