Python 字节码bytecode

字节码bytecode

dis模块是Python字节码反汇编器。通过反汇编支持Cpython的字节码分析。

前置知识

在看字节码之前,先要了解一下code object和frame object,它们在datamodel.html中有介绍

例子:

>>> import dis
>>> def hello():
...     print('Hello World!')
...
>>> hello.__code__
<code object hello at 0x1066683a0, file "<stdin>", line 1>

__code__属性显示了编译后的函数体the compiled function body, 它是一个code object

code object 代码对象

code模块中的code类产生code对象。

>>> type(hello.__code__)
<class 'code'>

code object一个python的内部类型。即解释器内部使用的类型。也称为bytecode。

code类有多个个data attributes(实例变量),其中:

  • co_consts  为一个包含字节码所使用的字面值的元组。如果code object代表一个函数,这个属性的第一项是函数的文档字符串。
  • co_varnames 为一个包含局部变量名称的元组。
  • 'co_names': <member 'co_names' of 'code' objects> 在函数体内引用的非本地name的tuple

详细介绍见:https://docs.python.org/3/reference/datamodel.html#object.__repr__

例子:

>>> hello.__code__.co_consts
(None, 'Hello World!')
 
>>> hello.__code__.co_varnames
()
>>> hello.__code__.co_names
('print',)

frame object

猜你喜欢

转载自www.cnblogs.com/chentianwei/p/12002967.html