4

我实际上需要xor我的解决方案,但在考虑它时,我开始想知道上面的问题。是什么意思True == True != False

查看文档,我认为它是True == True and True != False,但我想要一种更通用和确定的方法。我如何快速获得此类代码的可读形式的字节码。有没有比字节码和文档更容易找到的方法?

4

2 回答 2

11

这称为运算符链接A op1 B op2 C只要你有一个像withop1和compares 这样的表达式,op2它就会被“翻译”成A op1 B and B op2 C. (实际上它只评估B一次)。

注意:比较运算符包括in, not in, is, is not! (例如a is b is not None意味着a is b and b is not None)。

如果您想查看字节码,可以使用该dis模块:

In [1]: import dis

In [2]: dis.dis(lambda: True == True != False)
  1           0 LOAD_CONST               1 (True) 
              3 LOAD_CONST               1 (True) 
              6 DUP_TOP              
              7 ROT_THREE            
              8 COMPARE_OP               2 (==) 
             11 JUMP_IF_FALSE_OR_POP    21 
             14 LOAD_CONST               2 (False) 
             17 COMPARE_OP               3 (!=) 
             20 RETURN_VALUE         
        >>   21 ROT_TWO              
             22 POP_TOP              
             23 RETURN_VALUE 

If you read at the bytecode you can understand that it performs operator chaining.

Given that the expression is True == True != False, which is "interpreted" as True == True and True != False it first loads the two True constants for the first operator via the LOAD_CONST bytecode. The DUP_TOP duplicates the top of the stack(this avoids re-evaluating True for the second comparison). It performs the first comparison(COMPARE_OP) if it is false it just to the bytecode 21, otherwise it pops the top of the stack(JUMP_IF_FALSE_OR_POP). It then performs the second comparison.

To answer your general question the fastest way to find out about some feature of python is to use the quicksearch page of the documentation. I'd also suggest to read Python's tutorial for a general introduction to the language.

I'd like to add that, since python provides an interactive environment, it is often easier to understand how some code works writing it in the interpreter and watching the results. Almost all buil-in types have the documentation available via docstrings, so doing help(some_object) should give you a lot of information. In particular IPython provides an enhanced interactive interpreter with more user-friendly help messages/error formatting etc.)

于 2013-08-30T08:46:31.600 回答
5

在大多数语言中,a == b != c解析为(a == b) != c. 因此,您所期望的是True == True != False(True == True) != False, 计算结果为True != False, 计算结果为相同True

Python 有不同的含义,如下所示:

>>> True != False != False
False
>>> (True != False) != False
True

在 Python 中,a == b != c等价于(a == b) and (b != c). 这意味着True == True != False等价于(True == True) and (True != False),计算结果为True and True,计算结果为True

巧合的是,这两种含义(Python 和其他语言的含义)在这里给出了相同的结果,但应该谨慎。

于 2013-08-30T08:41:36.710 回答