Python的 - 逻辑评价顺序"若"声明 [英] Python - logical evaluation order in "if" statement

查看:141
本文介绍了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 evaluates x; if x 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 $。 (请参阅<一个href=\"http://docs.python.org/2/reference/datamodel.html#object.__nonzero__\"><$c$c>__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.)

    由于类不实现 __非零__()方法(也没有 __ 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 ,而不是适用。

    这篇关于Python的 - 逻辑评价顺序&QUOT;若&QUOT;声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆