Python 中布尔表达式的计算

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1452489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:17:27  来源:igfitidea点击:

Evaluation of boolean expressions in Python

pythonobjectboolean

提问by Casebash

What truth value do objects evaluate to in Python?

对象在 Python 中评估的真值是什么?

Related Questions

相关问题

回答by meder omuraliev

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None

  • False

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __nonzero__()or __len__()method, when that method returns the integer zero or bool value False.

All other values are considered true -- so objects of many types are always true. Operations and built-in functions that have a Boolean result always return 0 or Falsefor false and 1 or Truefor true, unless otherwise stated. (Important exception: the Boolean operations "or" and "and" always return one of their operands.)

任何对象都可以测试真值,用于 if 或 while 条件或作为下面布尔运算的操作数。以下值被认为是错误的:

  • 没有任何

  • 错误的

  • 任何数字类型的零,例如0, 0L, 0.0, 0j

  • 任何空序列,例如,'', (), []

  • 任何空映射,例如,{}

  • 用户定义类的实例,如果该类定义了一个__nonzero__()__len__()方法,当该方法返回整数零或布尔值时False

所有其他值都被认为是真——所以许多类型的对象总是真。除非另有说明,否则具有布尔结果的运算和内置函数始终返回 0 或Falsefalse 和 1 或Truetrue。(重要的例外:布尔运算“or”和“and”总是返回它们的操作数之一。)

https://docs.python.org/2/library/stdtypes.html#truth-value-testing

https://docs.python.org/2/library/stdtypes.html#truth-value-testing

And as mentioned, you can override with custom objects by modifying nonzero.

如前所述,您可以通过修改非零来覆盖自定义对象。

回答by Casebash

Update: Removed all duplicate infomation with Meder's post

更新:删除了 Meder 帖子中的所有重复信息

For custom objects in Python < 3.0 __nonzero__to change how it is evaluated. In Python 3.0 this is __bool__(Referenceby e-satis)

对于 Python < 3.0 中的自定义对象,__nonzero__更改其评估方式。在 Python 3.0 中这是__bool__参考e-satis)

It is important to understand what is meant by evaluate. One meaning is when an object is explicitly casting to a bool or implicitly cast by its location (in a if or while loop).

了解评估的含义很重要。一种含义是当对象显式转换为 bool 或按其位置隐式转换时(在 if 或 while 循环中)。

Another is == evalutation. 1==True, 0==False, nothing else is equal via ==.

另一个是 == 评估。1==True, 0==False, 没有其他东西通过 == 相等。

>>> None==False
False
>>> 1==True
True
>>> 0==False
True
>>> 2==False
False
>>> 2==True
False

Finally, for is, only True or False are themselves.

最后,因为是,只有 True 或 False 才是他们自己。