English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode compile() retourne un objet de code Python à partir du code source (chaîne ordinaire, chaîne de bytes ou objet AST).
La syntaxe de compile() est :
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=)}-1)
If the Python code is in string form or is an AST object, and you want to change it to a code object, use the compile() method.
can be used later such asexec() and eval()Class methods to call the code object returned by compile() method, which will execute the dynamically generated Python code.
source -Normal string, byte string, or AST object
filename-The file from which the code is read. If not read from a file, it can be named itself
mode- exec or eval or single.
eval -Accepts only one expression.
exec -It can use a code block with Python statements, classes, and functions, etc.
single -If it contains a single interactive statement
flags (optional) and dont_inherit (optional)-Specify which statements in the future will affect the compilation of the source code. Default value: 0
optimize (optional)-The optimization level of the compiler. Default value-1.
The compile() method returns a Python code object.
codeInString = 'a =', 5\nb=6\nsum=a+b\nprint("sum =",sum)' codeObejct = compile(codeInString, 'sumstring', 'exec') exec(codeObejct)
When running the program, the output is:
sum = 11
Here,source (source)is in the form of a normal string. ThisFilenameissumstringAnd the exec mode later allows the use of the exec() method.
The compile() method converts a string into a Python code object. Then the code object is executed using the exec() method.