tom*_*nez 3 python short-circuiting python-3.x nonetype
我知道比较 int 和 None 类型在 Python3 (3.6.1) 中无效,正如我在这里看到的:
>>> largest = None
>>> number = 5
>>> number > largest
TypeError: '>' not supported between instances of int and NoneType
Run Code Online (Sandbox Code Playgroud)
但在这个脚本中,它没有给出 TypeError。
largest = None
for number in [5, 20, 11]:
if largest is None or number > largest:
largest = number
Run Code Online (Sandbox Code Playgroud)
当我使用 python3 运行此脚本时,它运行时不会出现 TypeError。为什么?
你在见证short circuiting。
if largest is None or number > largest:
(1) or (2)
Run Code Online (Sandbox Code Playgroud)
当条件(1)被评估为真,条件(2)是不执行。在第一次迭代中,largest is None是True,所以整个表达式为真。
作为说明性示例,请考虑这个小片段。
test = 1
if test or not print('Nope!'):
pass
# Nothing printed
Run Code Online (Sandbox Code Playgroud)
现在,重复test=None:
test = None
if test or not print('Nope!'):
pass
Nope!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1740 次 |
| 最近记录: |