Python的 - 逻辑评价顺序"若"声明
在Python中,我们可以做到这一点:
In Python we can do this:
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
- 有人可以点我的文档此功能?
- 它是语言的实现细节或功能?
- 这是好编码风格利用此功能?
的或
和和
的短路的,请参见布尔运算文档:
The or
and and
short circuit, see the Boolean operations documentation:
这位前pression x和y
首先评估 X
;如果 X
是假的,它的值返回;否则,是
评估并返回结果值。
The expression
x and y
first evaluatesx
; ifx
is false, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
这位前pression x或y
首先评估 X
;如果 X
是真实的,它的值返回;否则,是
评估并返回结果值。
The expression x or y
first evaluates x
; if x
is true, its value is returned; otherwise, y
is evaluated and the resulting value is returned.
请注意如何,对于和
,是
终止的只有的评估,如果 X
计算为一个真正的价值。相反,对于或
,是
只有当评估 X
评估为False值。
Note how, for and
, y
is only evaluated if x
evaluates to a True value. Inversely, for or
, y
is only evaluated if x
evaluated to a False value.
有关第一八佰伴pression True或嗒嗒
,这意味着等等
是从来没有评估,因为第一部分是已真
。
For the first expression True or blah
, this means that blah
is never evaluated, since the first part is already True
.
此外,您的自定义胡说
类被认为是真实的:
Furthermore, your custom Blah
class is considered True:
在布尔运算的上下文,还当前pressions通过控制流语句使用,下面的值是相互preTED为假:假
,无
,所有类型的,和空字符串和容器(包括字符串,元组,列表,字典,集和frozensets)的数值为零。所有其他值都PTED为真际$ P $。 (请参阅__nonzero__()$c$c>一种方式,特殊的方法来改变这种情况。)
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:
False
,None
, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. (See the__nonzero__()
special method for a way to change this.)
由于类不实现 __非零__()
方法(也没有 __ LEN __
法),它被认为是真
据布尔前pressions关注。
Since your class does not implement a __nonzero__()
method (nor a __len__
method), it is considered True
as far as boolean expressions are concerned.
在除权pression 嗒嗒或blah.notexist
,等等
因此,真实的, blah.notexist
不会求。
In the expression blah or blah.notexist
, blah
is thus true, and blah.notexist
is never evaluated.
此功能是由经验丰富的开发相当定期和有效利用,最常指定默认值:
This feature is used quite regularly and effectively by experienced developers, most often to specify defaults:
some_setting = user_supplied_value or 'default literal'
object_test = is_it_defined and is_it_defined.some_attribute
千万要警惕这些链接,并使用有条件恩pression ,而不是适用。