Python - “if"中的逻辑评估顺序陈述

2022-01-19 00:00:00 python boolean short-circuiting

问题描述

在 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

  • 有人可以指点我有关此功能的文档吗?
  • 是语言的实现细节还是特性?
  • 利用此功能是一种好的编码风格吗?

  • 解决方案

    orand 短路,见布尔运算 文档:

    表达式x and y首先计算x;如果 x 为 false,则返回其值;否则,评估 y 并返回结果值.

    The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

    表达式x or y首先计算x;如果 x 为真,则返回其值;否则,评估 y 并返回结果值.

    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 的计算结果为 True 值,y 仅 被计算.相反,对于 ory 仅在 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.

    对于第一个表达式True or blah,这意味着永远不会评估blah,因为第一部分已经是True.

    For the first expression True or blah, this means that blah is never evaluated, since the first part is already True.

    此外,您的自定义 Blah 类被认为是 True:

    Furthermore, your custom Blah class is considered True:

    在布尔运算的上下文中,以及当控制流语句使用表达式时,以下值被解释为假:FalseNone、数字零所有类型,以及空字符串和容器(包括字符串、元组、列表、字典、集合和frozensets).所有其他值都被解释为 true.(参见 __nonzero__() 特殊方法改变这一点.)

    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.)

    由于您的类没有实现 __nonzero__() 方法(也没有实现 __len__ 方法),因此就布尔值而言,它被视为 True表达有关.

    Since your class does not implement a __nonzero__() method (nor a __len__ method), it is considered True as far as boolean expressions are concerned.

    在表达式 blah 或 blah.notexist 中,blah 因此为真,并且永远不会评估 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
    

    请小心链接这些内容,并在适用的情况下使用条件表达式.

    Do be wary of chaining these and use a conditional expression instead where applicable.

相关文章