Python 代码对象
代码对象是 CPython 实现的低级细节。每个代码对象都表示一段尚未绑定到函数中的可执行代码。虽然代码对象表示一段可执行代码,但它们本身并不能直接调用。如需执行代码对象,必须使用 exec 关键字。
在下面的示例中,我们将看到如何为给定的代码块创建代码对象,以及与该代码对象关联的各种属性。
示例
code_str = """
print("Hello Code Objects")
"""
# Create the code object
code_obj = compile(code_str, '<string>', 'exec')
# get the code object
print(code_obj)
#Attributes of code object
print(dir(code_obj))
# The filename
print(code_obj.co_filename)
# The first chunk of raw bytecode
print(code_obj.co_code)
#The variable Names
print(code_obj.co_varnames)输出
运行以上代码,得到以下结果 −
<code object <module> at 0x000001D80557EF50, file "<string>", line 2> ['__class__', '__delattr__', '__dir__', '__doc__', ……., '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', …..,posonlyargcount', 'co_stacksize', 'co_varnames', 'replace'] <string> b'e\x00d\x00\x83\x01\x01\x00d\x01S\x00' ()
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP