代码对象的默认__init__
-
02-01-2020 - |
题
我在Python中找到了代码对象。我很好奇构造函数中的每个变量都做了什么。在内置的帮助函数中没有太多关于它们的信息,我得到的只是:
class code(object)
| code(argcount, nlocals, stacksize, flags, codestring, constants, names,
| varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]])
|
| Create a code object. Not for the faint of heart.
这显然不是很有用。每个输入都期望什么类型,值做什么? 注意事项: 我问这个问题是出于学术上的好奇心,而不是为了任何特定的编码目的。
解决方案
Python代码对象主要只是其属性的容器。您为构造函数看到的每个参数都成为一个具有 co_
前缀(例如该 argcount
参数成为 co_argcount
属性)。
构造函数确实进行了一些验证,因此如果参数类型不正确,它将立即引发异常(而不是仅在稍后使用代码对象时失败)。
至于参数和属性的含义,这主要记录在一个大表中 的文件 inspect
模块.以下是相关部分:
code co_argcount number of arguments (not including * or ** args)
co_code string of raw compiled bytecode
co_consts tuple of constants used in the bytecode
co_filename name of file in which this code object was created
co_firstlineno number of first line in Python source code
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
co_lnotab encoded mapping of line numbers to bytecode indices
co_name name with which this code object was defined
co_names tuple of names of local variables
co_nlocals number of local variables
co_stacksize virtual machine stack space required
co_varnames tuple of names of arguments and local variables
属性 co_freevars
和 co_cellvars
据我所知没有记录。我想它们和闭包有关。
不隶属于 StackOverflow