Python: eval() v.s. exec() v.s. compile()

阅读 stackoverflow 上的问题: What's the difference between eval, exec, and compile in Python?

做一下小的总结:

  • eval() 接受 expression, 并返回其结果

  • exec() 接受statements, 返回值为 None

  • compile(): Compile the source into a code or AST object. Code objects can be executed by exec() or eval().

If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:

exec(compile(source, '<string>', 'exec'))

and eval similarly behaves equivalent to:

eval(compile(source, '<string>', 'eval'))

参考

python documentation: Built-in Functions

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。