Python—逻辑求值顺序为;如果;陈述
在Python中,我们可以这样做:Python—逻辑求值顺序为;如果;陈述,python,boolean,short-circuiting,Python,Boolean,Short Circuiting,在Python中,我们可以这样做: if True or blah: print("it's ok") # will be executed if blah or True: # will raise a NameError print("it's not ok") class Blah: pass blah = Blah() if blah or blah.notexist: print("it's ok") # also will be executed
if True or blah:
print("it's ok") # will be executed
if blah or True: # will raise a NameError
print("it's not ok")
class Blah:
pass
blah = Blah()
if blah or blah.notexist:
print("it's ok") # also will be executed
- 有人能给我指一下这个功能的文档吗
- 它是语言的实现细节还是特性
- 利用这个特性是一种好的编码方式吗
- 这称为短路,是该语言的一个特点:
布尔运算符
和
和或
是所谓的短路运算符:它们的参数从左到右求值,结果确定后求值立即停止。例如,如果A和C为true,但B为false,则A和B和C不会计算表达式C。当用作常规值而不是布尔值时,短路运算符的返回值是最后计算的参数
这是运算符逻辑运算符的工作方式,特别是python中的
或:短路求值。
为了更好地解释这一点,请考虑以下内容:
if True or False:
print('True') # never reaches the evaluation of False, because it sees True first.
if False or True:
print('True') # print's True, but it reaches the evaluation of True after False has been evaluated.
有关更多信息,请参见以下内容:
if True or False:
print('True') # never reaches the evaluation of False, because it sees True first.
if False or True:
print('True') # print's True, but it reaches the evaluation of True after False has been evaluated.
对于或和和短路,请参阅文档:
表达式x和y
首先计算x
;如果x
为false,则返回其值;否则,将计算y
,并返回结果值
表达式x或y
首先计算x
;如果x
为真,则返回其值;否则,将计算y
,并返回结果值
请注意,对于和
,y
仅在x
的计算结果为真值时才进行计算。相反,对于或
,y
仅在x
计算为假值时才进行计算
对于第一个表达式True或blah
,这意味着永远不会计算blah
,因为第一部分已经是True
此外,您的自定义Blah
类被认为是正确的:
在布尔运算的上下文中,以及当控制流语句使用表达式时,以下值被解释为false:false
、None
、所有类型的数字零以及空字符串和容器(包括字符串、元组、列表、字典、集合和冻结集)。所有其他值都被解释为true。(有关更改此设置的方法,请参见特殊方法。)
由于您的类没有实现\uuu非零方法(
方法,也没有\uuu len\uuu
方法),因此就布尔表达式而言,它被认为是True
在表达式blah或blah.notexist
中,blah
因此是真的,并且blah.notexist
永远不会被计算
经验丰富的开发人员经常有效地使用此功能,通常用于指定默认值:
some_setting = user_supplied_value or 'default literal'
object_test = is_it_defined and is_it_defined.some_attribute
一定要小心将这些链接起来,并在适用的情况下使用链接 使用或操作符,从左到右计算值。在一个值的计算结果为True
之后,整个语句的计算结果为True
(因此不再计算其他值)
- 这是语言的一个特点
- 使用它的功能没有什么错
blah或True
one不会为我引发异常,它会打印。@TimS.:仅当您首先定义blah
时。请注意,blah
尚未在示例顶部定义,因此会引发namererror
。