Python 代码对象 - 它们的用途是什么?
Python 代码对象有什么用途?除了被解释器或调试器使用之外,它们还有哪些其他有用的用途?
您是否直接与代码对象交互过?如果是,在什么情况下?
What are the uses of Python code objects? Besides being used by the interpreter or debugger what other useful usages do they have?
Have you interacted directly with code objects? If yes, in what situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
代码对象的主要用途是将函数(代码)的静态部分与动态部分(函数)分开。代码对象是隐藏在 .pyc 文件中的东西,是在编译代码时创建的;函数对象是在运行时声明函数时从它们创建的。它们是为调试器反射而公开的,通常不需要直接使用。
所有支持闭包的语言都有类似的东西;他们只是并不总是像使用 Python 那样接触该语言,Python 比大多数语言具有更全面的反映。
您可以使用代码对象通过
types.FunctionType
实例化函数对象,但这很少有任何实际用途 - 换句话说,不要这样做:The primary use of code objects is to separate the static parts of functions (code) from the dynamic parts (functions). Code objects are the things that are stashed in .pyc files, and are created when code is compiled; function objects are created from them at runtime when functions are declared. They're exposed for debugger reflection and don't often need to be used directly.
All languages that support closures have something like them; they're just not always exposed to the language as they are in Python, which has more comprehensive reflection than most languages.
You can use code objects to instantiate function objects via
types.FunctionType
, but that very rarely has any practical use--in other words, don't do this:如果你想 pickle 函数,你可以使用它们。
两个食谱:
http://code.activestate.com/recipes /572213-pickle-the-interactive-interpreter-state/
http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-7-sect-6.html
You can use them if you want to pickle functions.
two recipes:
http://code.activestate.com/recipes/572213-pickle-the-interactive-interpreter-state/
http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-7-sect-6.html
当您使用内置的 compile 函数 时,它将返回一个代码对象,例如这:
就我个人而言,我在支持不同插件脚本的应用程序中使用了它:我只需从文件中读取插件,将其传递给编译函数,然后在需要时使用 exec 运行它,这具有速度提升的优点,因为您只需将其编译为字节代码一次。
When you use the built-in compile function it will return a code object, like this:
Personally, I've used this in applications that supports scripting in different plug-ins: I would just read the plug-in from a file, pass it to the compile function and then use exec to run it whenever it was needed, which gives the advantage of a speed boost as you only have to compile it once to byte code.