list1AndCompile

列表生成式与编译:

a = [i*2 for i in range(10)]
# 列表生成式,使代码更简洁,具有以下三行的效果
# a = []
# for i in range(10)
#   a.append(i*2)
print(a)


code_test = '''a = [i*2 for i in range(10)]
print('This is manual compiling:', a)
'''
py_obj = compile(code_test, 'file1.txt', 'exec')
exec(code_test)
exec(py_obj)
eval(py_obj)  # eval的功能包含exec,所以能直接用
# 这实际就是底层编译的功能,可以直接调用
# 那么这里自己重新编写,是因为可以实现动态编译功能,比如对别人传过来的代码编译
code_test1 = "3+2**3-5"
py_obj1 = compile(code_test1, '', 'eval')
print(eval(code_test1))  # 不用print的话,只执行没有输出
print(eval(py_obj1))
py_obj1_1 = compile(code_test1, '', 'exec')
print(exec(py_obj1_1))  # 输出None,eval还可以用来计算

 

posted @ 2020-09-25 16:46  龚志军Flagon  阅读(110)  评论(0编辑  收藏  举报