在Python中,and
和or
都将返回其操作数之一。使用or
,Python会检查第一个操作数,如果它是一个“真实的”值(稍后会提供更多有关真实性的信息),它将返回第一个值而不检查第二个值(这称为布尔快捷方式评估,这可能很重要)。如果第一个为“ falsey”,则Python返回第二个操作数,无论它是什么:
Python 2.7.3 (default, Jan 2 2013, 13:56:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 or 3
2
>>> 0 or 3
3
使用“ and”,会发生很多相同的事情:首先检查第一个操作数,如果它是“ false”,则Python永远不会检查第二个操作数。如果第一个操作数是“ truthy”,则Python返回第二个操作数,无论它是什么:
>>> 2 and 3
3
>>> 0 and 3
0
>>> 3 and 0
0
>>> 3 and []
[]
>>> 0 and []
0
现在让我们谈谈“真实性”和“虚假性”。Python使用以下规则在布尔上下文中评估事物:
因此,类似的东西password and PASS_RE.match(password)
正在利用Python的短路评估功能。如果password
为None,则and
运算符将仅返回None,并且从不评估下半部分。很好,因为PASS_RE.match(None)
会引发异常。看这个:
>>> 3 or []
3
>>> [] or 3
3
>>> 0 or []
[]
>>> [] or 0
0
>>> 0 and []
0
>>> [] and 0
[]
看看短路是如何工作的?现在看这个:
>>> value = "hello"
>>> print (value.upper())
HELLO
>>> print (value and value.upper())
HELLO
>>> value = None
>>> print (value.upper())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'nonetype' object has no attribute 'upper'
>>> print (value and value.upper())
None