使用 Python 3:
>>> a = []
>>> f = print(
a.append(1), a[:],
a.append(2), a[:],
a.append(3), a[:]
)
None [1] None [1, 2] None [1, 2, 3]
档案:
>>> a = []
>>> f = print(a.append(1), a, a.append(2), a, a.append(3), a)
奇怪的是(起初),这段代码产生了:
None [1, 2, 3] None [1, 2, 3] None [1, 2, 3]
但是,dis(f)
使这一点更清楚:
>>> dis(f)
1 0 LOAD_NAME 0 (print) #Loads the value of 'print' into memory. Precisely, the value is pushed to the TOS (Top of Stack)
--> 3 LOAD_NAME 1 (a) #Loads the value of object 'a'
6 LOAD_ATTR 2 (append) #Loads the append attribute (in this case method)
9 LOAD_CONST 0 (1) #Loads the constant 1
12 CALL_FUNCTION 1 #a.append(1) is called
15 LOAD_NAME 1 (a) #for print(...,a,...)
18 LOAD_NAME 1 (a) #for the next a.append()
21 LOAD_ATTR 2 (append)
24 LOAD_CONST 1 (2)
27 CALL_FUNCTION 1 #a.append(2)
30 LOAD_NAME 1 (a)
33 LOAD_NAME 1 (a)
36 LOAD_ATTR 2 (append)
39 LOAD_CONST 2 (3)
42 CALL_FUNCTION 1 #a.append(3)
45 LOAD_NAME 1 (a) #loads a to be used thrice by print
48 CALL_FUNCTION 6 #calls print
51 PRINT_EXPR #prints TOS and clears it
52 LOAD_CONST 3 (None) #Loads None
55 RETURN_VALUE #Returns None
的输出dis(f)
是我们所期望的——从左到右的评估。本质上,这种“差异”是print()
最后评估的结果。到那时, 的值a
已更改为[1, 2, 3]
并且相同的最终对象被打印三次。
如果我们用 替换a
,a[:]
我们会得到预期的结果。