1 in [] in 'a'计算为(1 in []) and ([] in 'a')。在
由于第一个条件(1 in [])是False,因此整个条件的计算结果为False;([] in 'a')从未实际计算,因此不会产生错误。在
以下是语句定义:In [121]: def func():
.....: return 1 in [] in 'a'
.....:
In [122]: dis.dis(func)
2 0 LOAD_CONST 1 (1)
3 BUILD_LIST 0
6 DUP_TOP
7 ROT_THREE
8 COMPARE_OP 6 (in)
11 JUMP_IF_FALSE 8 (to 22) #if first comparison is wrong
#then jump to 22,
14 POP_TOP
15 LOAD_CONST 2 ('a')
18 COMPARE_OP 6 (in) #this is never executed, so no Error
21 RETURN_VALUE
>> 22 ROT_TWO
23 POP_TOP
24 RETURN_VALUE
In [150]: def func1():
.....: return (1 in []) in 'a'
.....:
In [151]: dis.dis(func1)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 3 (())
6 COMPARE_OP 6 (in) # perform 1 in []
9 LOAD_CONST 2 ('a') # now load 'a'
12 COMPARE_OP 6 (in) # compare result of (1 in []) with 'a'
# throws Error coz (False in 'a') is
# TypeError
15 RETURN_VALUE
In [153]: def func2():
.....: return 1 in ([] in 'a')
.....:
In [154]: dis.dis(func2)
2 0 LOAD_CONST 1 (1)
3 BUILD_LIST 0
6 LOAD_CONST 2 ('a')
9 COMPARE_OP 6 (in) # perform ([] in 'a'), which is
# Incorrect, so it throws TypeError
12 COMPARE_OP 6 (in) # if no Error then
# compare 1 with the result of ([] in 'a')
15 RETURN_VALUE