7

PEP 622,文字模式说如下:

请注意,由于使用了相等 (__eq__),以及布尔值与整数 0 和 1 之间的等价性,因此以下两者之间没有实际区别:

case True:
    ...

case 1:
    ...

and True.__eq__(1)and(1).__eq__(True)都返回 True,但是当我用 CPython 运行这两个代码片段时,它看起来case Truecase 1不一样。

$ python3.10
>>> match 1:
...     case True:
...         print('a')  # not executed
... 
>>> match True:
...     case 1:
...         print('a')  # executed
... 
a

如何1True实际进行比较?

4

1 回答 1

10

查看模式匹配规范,这属于“文字模式”

如果使用以下比较规则,主题值比较等于由文字表示的值,则文字模式成功:

  • 使用 == 运算符比较数字和字符串。
  • 使用 is 运算符比较单例文字 None、True 和 False。

所以当模式是:

 case True:

它使用is, 并且1 is True是错误的。另一方面,

case 1:

使用==, 并且1 == True是真的。

于 2021-10-14T22:06:28.890 回答