Python 代码对象 - 它们的用途是什么?

发布于 2024-10-18 08:51:59 字数 170 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苏佲洛 2024-10-25 08:51:59

代码对象的主要用途是将函数(代码)的静态部分与动态部分(函数)分开。代码对象是隐藏在 .pyc 文件中的东西,是在编译代码时创建的;函数对象是在运行时声明函数时从它们创建的。它们是为调试器反射而公开的,通常不需要直接使用。

所有支持闭包的语言都有类似的东西;他们只是并不总是像使用 Python 那样接触该语言,Python 比大多数语言具有更全面的反映。

您可以使用代码对象通过 types.FunctionType 实例化函数对象,但这很少有任何实际用途 - 换句话说,不要这样做:

def func(a=1):
    print a

func2 = types.FunctionType(func.func_code, globals(), 'func2', (2,))
func2()
# 2

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:

def func(a=1):
    print a

func2 = types.FunctionType(func.func_code, globals(), 'func2', (2,))
func2()
# 2
戈亓 2024-10-25 08:51:59

当您使用内置的 compile 函数 时,它将返回一个代码对象,例如这:

>>> c = compile("print 'Hello world'", "string", "exec")
<code object <module> at 0xb732a4e8, file "string", line 1>
>>> exec(c)
Hello world
>>> 

就我个人而言,我在支持不同插件脚本的应用程序中使用了它:我只需从文件中读取插件,将其传递给编译函数,然后在需要时使用 exec 运行它,这具有速度提升的优点,因为您只需将其编译为字节代码一次。

When you use the built-in compile function it will return a code object, like this:

>>> c = compile("print 'Hello world'", "string", "exec")
<code object <module> at 0xb732a4e8, file "string", line 1>
>>> exec(c)
Hello world
>>> 

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文