这是我的代码:
x=100
def foo(m, n=66):
return m + n
b=200
a=foo(x) + b
print(a)
这是反汇编的:
$ python3 -m dis test_func.py
1 0 LOAD_CONST 0 (100)
2 STORE_NAME 0 (x)
2 4 LOAD_CONST 6 ((66,))
6 LOAD_CONST 2 (<code object foo at 0x7f2c7dba39c0, file "test_func.py", line 2>)
8 LOAD_CONST 3 ('foo')
10 MAKE_FUNCTION 1
12 STORE_NAME 1 (foo)
5 14 LOAD_CONST 4 (200)
16 STORE_NAME 2 (b)
6 18 LOAD_NAME 1 (foo)
20 LOAD_NAME 0 (x)
22 CALL_FUNCTION 1
24 LOAD_NAME 2 (b)
26 BINARY_ADD
28 STORE_NAME 3 (a)
7 30 LOAD_NAME 4 (print)
32 LOAD_NAME 3 (a)
34 CALL_FUNCTION 1
36 POP_TOP
38 LOAD_CONST 5 (None)
40 RETURN_VALUE
我的问题围绕这一部分:
2 4 LOAD_CONST 6 ((66,))
6 LOAD_CONST 2 (<code object foo at 0x7f2c7dba39c0, file "test_func.py", line 2>)
8 LOAD_CONST 3 ('foo')
10 MAKE_FUNCTION 1
以下是document中有关MAKE_FUNCTION的摘录:
MAKE_FUNCTION(argc)
Pushes a new function object on the stack. From bottom to top, the consumed stack must consist of values if the argument carries a specified flag value:
0x01 a tuple of default values for positional-only and positional-or-keyword parameters in positional order
0x02 a dictionary of keyword-only parameters’ default values
0x04 an annotation dictionary
0x08 a tuple containing cells for free variables, making a closure
the code associated with the function (at TOS1)
the qualified name of the function (at TOS)
我很难解释这些标志:我在反汇编中看不到任何标志。
所以让我们将反汇编与doc相关联,当它运行到MAKE_FUNCTION时,堆栈深度为3:
1. the top is "foo" which comes from instruction @8
2. the next one is code object which comes from instruction @6
3. the bottom one is 66 which comes from instruction @4
现在我的问题是,该字节码中的“标志”在哪里?我的意思是文档中提到的0x01、0x02、0x04和/或0x08。 @ 4指令中的那个“ 6”吗?但是6是2和4,而这里只是位置参数……
请帮忙。
谢谢!
答案 0 :(得分:0)
标志是MAKE_FUNCTION
指令的参数:
10 MAKE_FUNCTION 1
标志为1
,即0x01
。