嵌套的 if 等于和逻辑吗?

Sor*_*h n 1 python logic if-statement nested

我想知道这两个Python代码是否总是相同的。

if condition_1:
    if condition_2:
        some_process
Run Code Online (Sandbox Code Playgroud)

if condition_1 and condition_2:
    some_process
Run Code Online (Sandbox Code Playgroud)

我搜索过但没有找到这个问题的具体答案。因此,例如,您正在尝试评估一个变量,但无法确定该变量是否存在。因此,首先应该检查变量是否存在。我们可以在评估的同时使用带有“与”逻辑的变量存在检查吗?它总是适用吗?

Bri*_*ian 5

是的,它们总是等价的。事实上,它们编译为完全相同的字节码,仅在某些元数据上有所不同1

# Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0]
# Type 'copyright', 'credits' or 'license' for more information
# IPython 7.31.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: def v1():
   ...:     if x:
   ...:         if y:
   ...:             pass
   ...: 

In [2]: def v2():
   ...:     if x and y:
   ...:         pass
   ...: 

In [3]: import dis

In [4]: dis.dis(v1)
  2           0 LOAD_GLOBAL              0 (x)
              2 POP_JUMP_IF_FALSE        7 (to 14)

  3           4 LOAD_GLOBAL              1 (y)
              6 POP_JUMP_IF_FALSE        9 (to 18)

  4           8 NOP
             10 LOAD_CONST               0 (None)
             12 RETURN_VALUE

  2     >>   14 LOAD_CONST               0 (None)
             16 RETURN_VALUE

  3     >>   18 LOAD_CONST               0 (None)
             20 RETURN_VALUE

In [5]: dis.dis(v2)
  2           0 LOAD_GLOBAL              0 (x)
              2 POP_JUMP_IF_FALSE        7 (to 14)
              4 LOAD_GLOBAL              1 (y)
              6 POP_JUMP_IF_FALSE        9 (to 18)

  3           8 NOP
             10 LOAD_CONST               0 (None)
             12 RETURN_VALUE

  2     >>   14 LOAD_CONST               0 (None)
             16 RETURN_VALUE
        >>   18 LOAD_CONST               0 (None)
             20 RETURN_VALUE

In [6]: v1.__code__.co_code == v2.__code__.co_code
Out[6]: True

Run Code Online (Sandbox Code Playgroud)

1 即函数代码对象的co_nameco_linetable、 和co_lnotab属性,不影响代码的执行。查看输出

import types
print( 
    {
        attr: (
            getattr(v1.__code__, attr),
            getattr(v2.__code__, attr),
        )
        for attr in dir(types.CodeType) if "co_" in attr
    }
)
Run Code Online (Sandbox Code Playgroud)

有关函数各自代码对象的详细比较。