gpt4 book ai didi

Python - "if"语句中的逻辑评估顺序

转载 作者:太空狗 更新时间:2023-10-29 19:31:08 24 4
gpt4 key购买 nike

在 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
  • 有人可以指点我有关此功能的文档吗?
  • 它是语言的实现细节或功能吗?
  • 利用此功能的编码风格是否良好?

最佳答案

orand 短路,见Boolean operations文档:

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.

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.

注意如何,对于 and , y x 时计算评估为真值。相反,对于 or , y仅在 x 时评估评估为 False 值。

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

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

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就 boolean 表达式而言。

在表达式 blah or blah.notexist 中, blah因此是真实的,并且blah.notexist永远不会被评估。

经验丰富的开发人员经常有效地使用此功能,最常用于指定默认值:

some_setting = user_supplied_value or 'default literal'
object_test = is_it_defined and is_it_defined.some_attribute

小心链接这些并使用 conditional expression相反,在适用的情况下。

关于Python - "if"语句中的逻辑评估顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16069517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com