十六、complie方法
1、定义:
compile(...)
compile(source, filename, mode[, flags[, dont_inherit]]) -> code object
Compile the source string (a Python module, statement or expression)
into a code object that can be executed by the exec statement or eval().
The filename will be used for run-time error messages.
The mode must be 'exec' to compile a module, 'single' to compile a
single (interactive) statement, or 'eval' to compile an expression.
The flags argument, if present, controls which future statements influence
the compilation of the code.
The dont_inherit argument, if non-zero, stops the compilation inheriting
the effects of any future statements in effect in the code calling
compile; if absent or zero these statements do influence the compilation,
in addition to any features explicitly specified. 2、解释:将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。
3、举例:
例1:
>>> code = "for i in range(0, 10): print i"
>>> cmpcode = compile(code, '', 'exec')
>>> exec cmpcode
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17
例2:
test.cfg内容如下:
SQLALCHEMY_POOL_RECYCLE = 10
SQLALCHEMY_ECHO = False
filename = 'test.cfg'
_dict = {}
with open(filename) as config_file:
code_obj = compile(config_file.read(), '', 'exec')
exec(code_obj, _dict)
print _dict.get('SQLALCHEMY_POOL_RECYCLE')
print _dict.get('SQLALCHEMY_ECHO')
输出:
10
False
因此_dict 变量获得了test.cfg文件中的配置信息 十七、complex类
1、定义:
class complex(object) | complex(real[, imag]) -> complex number | | Create a complex number from a real part and an optional imaginary part. | This is equivalent to (real + imag*1j) where imag defaults to 0.
2、解释:生成一个复数
3、举例:
>>> complex(1,5) (1+5j) >>> complex(1) (1+0j) >>> complex(1,-5) (1-5j)
Copyright © 2021.aoyanming个人博客站
发表评论